Revert "feat: fix the problem in the Operator Market frontend pages" (#204)

Reverts ModelEngine-Group/DataMate#203
This commit is contained in:
Kecheng Sha
2025-12-29 12:01:19 +08:00
committed by GitHub
213 changed files with 45537 additions and 45547 deletions

View File

@@ -1,13 +1,13 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.{md}]
trim_trailing_whitespace = false
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.{md}]
trim_trailing_whitespace = false

54
frontend/.gitignore vendored
View File

@@ -1,28 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
src/mock/sessions/*
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
src/mock/sessions/*
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.vite

View File

@@ -1,96 +1,96 @@
🚀 快速开始
```
npm install # 安装依赖
npm run dev # 启动项目
npm run mock # 启动后台Mock服务(可选)
```
📁 项目结构
```
frontend/
├── public/ # 📖 文档中心
│ ├── huawei-logo.webp/ # logo
│ └── xxx/ # 标注工作台(可分离部署)
├── src/ # 🎨 前端应用
│ ├── apps/ # 多前端应用
│ │ ├── console/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ ├── package.json
│ │ │ └── src/
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── assets/ # 共享UI组件/SDK
│ │ ├── xxx/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ └── src/
│ │ │
│ │ │
│ │ └── xxx/ # 数据工作台&运营控制台
│ │ ├── package.json
│ │ └── src/
│ │
│ ├── components/ # 构建与环境配置
│ │ ├── CardView.tsx # 数据工作台&运营控制台
│ │ ├── DetailHeader.tsx # 数据工作台&运营控制台
│ │ ├── RadioCard.tsx # 数据工作台&运营控制台
│ │ ├── SearchControls # 数据工作台&运营控制台
│ │ ├── TagList # 标注工作台(可分离部署)
│ │ └── TaskPopover # 标注工作台(可分离部署)
│ │
│ ├── hooks/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── mock/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── pages/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ ├── package.json
│ │ │ └── src/
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── providers/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ ├── package.json
│ │ │ └── src/
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── routes/ # 构建与环境配置
│ │ └── next.config.js
│ │
│ ├── types/ # 构建与环境配置
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ └── next.config.js
│ │
│ └── utils/ # 构建与环境配置
│ ├── next.config.js
│ ├── next.config.js
│ └── next.config.js
├── eslint.config.js/ # 🔧 后端服务架构
├── index.html/ # 🔧 后端服务架构
├── package.json/ # 🔧 后端服务架构
├── README.md # 项目说明
├── tailwind.config.ts # 更新日志
├── vite.config.ts # 开源协议
└── pom.xml # Maven根配置
```
🚀 快速开始
```
npm install # 安装依赖
npm run dev # 启动项目
npm run mock # 启动后台Mock服务(可选)
```
📁 项目结构
```
frontend/
├── public/ # 📖 文档中心
│ ├── huawei-logo.webp/ # logo
│ └── xxx/ # 标注工作台(可分离部署)
├── src/ # 🎨 前端应用
│ ├── apps/ # 多前端应用
│ │ ├── console/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ ├── package.json
│ │ │ └── src/
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── assets/ # 共享UI组件/SDK
│ │ ├── xxx/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ └── src/
│ │ │
│ │ │
│ │ └── xxx/ # 数据工作台&运营控制台
│ │ ├── package.json
│ │ └── src/
│ │
│ ├── components/ # 构建与环境配置
│ │ ├── CardView.tsx # 数据工作台&运营控制台
│ │ ├── DetailHeader.tsx # 数据工作台&运营控制台
│ │ ├── RadioCard.tsx # 数据工作台&运营控制台
│ │ ├── SearchControls # 数据工作台&运营控制台
│ │ ├── TagList # 标注工作台(可分离部署)
│ │ └── TaskPopover # 标注工作台(可分离部署)
│ │
│ ├── hooks/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── mock/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── pages/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ ├── package.json
│ │ │ └── src/
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── providers/ # 构建与环境配置
│ │ ├── console/ # 数据工作台&运营控制台
│ │ │ ├── next.config.js
│ │ │ ├── package.json
│ │ │ └── src/
│ │ └── annotation-studio/ # 标注工作台(可分离部署)
│ │
│ ├── routes/ # 构建与环境配置
│ │ └── next.config.js
│ │
│ ├── types/ # 构建与环境配置
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ ├── next.config.js
│ │ └── next.config.js
│ │
│ └── utils/ # 构建与环境配置
│ ├── next.config.js
│ ├── next.config.js
│ └── next.config.js
├── eslint.config.js/ # 🔧 后端服务架构
├── index.html/ # 🔧 后端服务架构
├── package.json/ # 🔧 后端服务架构
├── README.md # 项目说明
├── tailwind.config.ts # 更新日志
├── vite.config.ts # 开源协议
└── pom.xml # Maven根配置
```

View File

@@ -1,23 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

View File

@@ -1,13 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/huawei-logo.webp" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DataMate</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/huawei-logo.webp" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DataMate</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

14450
frontend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,51 +1,51 @@
{
"name": "edatamate",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"mock": "cd src/mock && nodemon --config nodemon.json --inspect=0.0.0.0:9229 mock.cjs --env=development --port=8002",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@reduxjs/toolkit": "^2.11.0",
"@xyflow/react": "^12.8.3",
"antd": "^5.27.0",
"jssha": "^3.3.1",
"lucide-react": "^0.539.0",
"react": "^18.1.1",
"react-dom": "^18.1.1",
"react-redux": "^9.2.0",
"react-router": "^7.8.0",
"recharts": "2.15.0"
},
"devDependencies": {
"@eslint/js": "^9.33.0",
"@tailwindcss/vite": "^4.1.12",
"@types/node": "^24.2.1",
"@types/react": "^18.1.10",
"@types/react-dom": "^18.1.7",
"@vitejs/plugin-react": "^5.0.0",
"body-parser": "^2.2.0",
"eslint": "^9.33.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"express": "^5.1.0",
"express-session": "^1.18.2",
"fs-extra": "^11.3.1",
"globals": "^16.3.0",
"lodash": "^4.17.21",
"minimist": "^1.2.8",
"mockjs": "^1.1.0",
"nodemon": "^3.1.10",
"postcss": "^8.5.6",
"session-file-store": "^1.5.0",
"tailwindcss": "^4.1.12",
"typescript": "~5.8.3",
"typescript-eslint": "^8.39.1",
"vite": "^7.1.2"
}
}
{
"name": "edatamate",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"mock": "cd src/mock && nodemon --config nodemon.json --inspect=0.0.0.0:9229 mock.cjs --env=development --port=8002",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@reduxjs/toolkit": "^2.11.0",
"@xyflow/react": "^12.8.3",
"antd": "^5.27.0",
"jssha": "^3.3.1",
"lucide-react": "^0.539.0",
"react": "^18.1.1",
"react-dom": "^18.1.1",
"react-redux": "^9.2.0",
"react-router": "^7.8.0",
"recharts": "2.15.0"
},
"devDependencies": {
"@eslint/js": "^9.33.0",
"@tailwindcss/vite": "^4.1.12",
"@types/node": "^24.2.1",
"@types/react": "^18.1.10",
"@types/react-dom": "^18.1.7",
"@vitejs/plugin-react": "^5.0.0",
"body-parser": "^2.2.0",
"eslint": "^9.33.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"express": "^5.1.0",
"express-session": "^1.18.2",
"fs-extra": "^11.3.1",
"globals": "^16.3.0",
"lodash": "^4.17.21",
"minimist": "^1.2.8",
"mockjs": "^1.1.0",
"nodemon": "^3.1.10",
"postcss": "^8.5.6",
"session-file-store": "^1.5.0",
"tailwindcss": "^4.1.12",
"typescript": "~5.8.3",
"typescript-eslint": "^8.39.1",
"vite": "^7.1.2"
}
}

View File

@@ -1,117 +1,117 @@
import { Dropdown, Popconfirm, Button, Space } from "antd";
import { EllipsisOutlined } from "@ant-design/icons";
import { useState } from "react";
interface ActionItem {
key: string;
label: string;
icon?: React.ReactNode;
danger?: boolean;
confirm?: {
title: string;
description?: string;
okText?: string;
cancelText?: string;
};
}
interface ActionDropdownProps {
actions?: ActionItem[];
onAction?: (key: string, action: ActionItem) => void;
placement?:
| "bottomRight"
| "topLeft"
| "topCenter"
| "topRight"
| "bottomLeft"
| "bottomCenter"
| "top"
| "bottom";
}
const ActionDropdown = ({
actions = [],
onAction,
placement = "bottomRight",
}: ActionDropdownProps) => {
const [open, setOpen] = useState(false);
const handleActionClick = (action: ActionItem) => {
if (action.confirm) {
// 如果有确认框,不立即执行,等待确认
return;
}
// 执行操作
onAction?.(action.key, action);
// 如果没有确认框,则立即关闭 Dropdown
setOpen(false);
};
const dropdownContent = (
<div className="bg-white p-2 rounded shadow-md">
<Space direction="vertical" className="w-full">
{actions.map((action) => {
if (action.confirm) {
return (
<Popconfirm
key={action.key}
title={action.confirm.title}
description={action.confirm.description}
onConfirm={() => {
onAction?.(action.key, action);
setOpen(false);
}}
okText={action.confirm.okText || "确定"}
cancelText={action.confirm.cancelText || "取消"}
okType={action.danger ? "danger" : "primary"}
styles={{ root: { zIndex: 9999 } }}
>
<Button
type="text"
size="small"
disabled={action.disabled || false}
className="w-full text-left"
danger={action.danger}
icon={action.icon}
>
{action.label}
</Button>
</Popconfirm>
);
}
return (
<Button
key={action.key}
className="w-full"
size="small"
type="text"
disabled={action.disabled || false}
danger={action.danger}
icon={action.icon}
onClick={() => handleActionClick(action)}
>
{action.label}
</Button>
);
})}
</Space>
</div>
);
return (
<Dropdown
overlay={dropdownContent}
trigger={["click"]}
placement={placement}
open={open}
onOpenChange={setOpen}
>
<Button
type="text"
icon={<EllipsisOutlined style={{ fontSize: 24 }} />}
/>
</Dropdown>
);
};
export default ActionDropdown;
import { Dropdown, Popconfirm, Button, Space } from "antd";
import { EllipsisOutlined } from "@ant-design/icons";
import { useState } from "react";
interface ActionItem {
key: string;
label: string;
icon?: React.ReactNode;
danger?: boolean;
confirm?: {
title: string;
description?: string;
okText?: string;
cancelText?: string;
};
}
interface ActionDropdownProps {
actions?: ActionItem[];
onAction?: (key: string, action: ActionItem) => void;
placement?:
| "bottomRight"
| "topLeft"
| "topCenter"
| "topRight"
| "bottomLeft"
| "bottomCenter"
| "top"
| "bottom";
}
const ActionDropdown = ({
actions = [],
onAction,
placement = "bottomRight",
}: ActionDropdownProps) => {
const [open, setOpen] = useState(false);
const handleActionClick = (action: ActionItem) => {
if (action.confirm) {
// 如果有确认框,不立即执行,等待确认
return;
}
// 执行操作
onAction?.(action.key, action);
// 如果没有确认框,则立即关闭 Dropdown
setOpen(false);
};
const dropdownContent = (
<div className="bg-white p-2 rounded shadow-md">
<Space direction="vertical" className="w-full">
{actions.map((action) => {
if (action.confirm) {
return (
<Popconfirm
key={action.key}
title={action.confirm.title}
description={action.confirm.description}
onConfirm={() => {
onAction?.(action.key, action);
setOpen(false);
}}
okText={action.confirm.okText || "确定"}
cancelText={action.confirm.cancelText || "取消"}
okType={action.danger ? "danger" : "primary"}
styles={{ root: { zIndex: 9999 } }}
>
<Button
type="text"
size="small"
disabled={action.disabled || false}
className="w-full text-left"
danger={action.danger}
icon={action.icon}
>
{action.label}
</Button>
</Popconfirm>
);
}
return (
<Button
key={action.key}
className="w-full"
size="small"
type="text"
disabled={action.disabled || false}
danger={action.danger}
icon={action.icon}
onClick={() => handleActionClick(action)}
>
{action.label}
</Button>
);
})}
</Space>
</div>
);
return (
<Dropdown
overlay={dropdownContent}
trigger={["click"]}
placement={placement}
open={open}
onOpenChange={setOpen}
>
<Button
type="text"
icon={<EllipsisOutlined style={{ fontSize: 24 }} />}
/>
</Dropdown>
);
};
export default ActionDropdown;

View File

@@ -1,134 +1,134 @@
import { Button, Input, Popover, theme, Tag, Empty } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useEffect, useMemo, useState } from "react";
interface Tag {
id: number;
name: string;
color: string;
}
interface AddTagPopoverProps {
tags: Tag[];
onFetchTags?: () => Promise<Tag[]>;
onAddTag?: (tag: Tag) => void;
onCreateAndTag?: (tagName: string) => void;
}
export default function AddTagPopover({
tags,
onFetchTags,
onAddTag,
onCreateAndTag,
}: AddTagPopoverProps) {
const { token } = theme.useToken();
const [showPopover, setShowPopover] = useState(false);
const [newTag, setNewTag] = useState("");
const [allTags, setAllTags] = useState<Tag[]>([]);
const tagsSet = useMemo(() => new Set(tags.map((tag) => tag.id)), [tags]);
const fetchTags = async () => {
if (onFetchTags && showPopover) {
const data = await onFetchTags?.();
setAllTags(data || []);
}
};
useEffect(() => {
fetchTags();
}, [showPopover]);
const availableTags = useMemo(() => {
return allTags.filter((tag) => !tagsSet.has(tag.id));
}, [allTags, tagsSet]);
const handleCreateAndAddTag = () => {
if (newTag.trim()) {
onCreateAndTag?.(newTag.trim());
setNewTag("");
}
setShowPopover(false);
};
const tagPlusStyle: React.CSSProperties = {
height: 22,
background: token.colorBgContainer,
borderStyle: "dashed",
};
return (
<>
<Popover
open={showPopover}
trigger="click"
placement="bottom"
onOpenChange={setShowPopover}
content={
<div className="space-y-4 w-[300px]">
<h4 className="font-medium border-b pb-2 border-gray-100">
</h4>
{/* Available Tags */}
{availableTags?.length ? (
<div className="space-y-2">
<h5 className="text-sm"></h5>
<div className="max-h-32 overflow-y-auto space-y-1">
{availableTags.map((tag) => (
<span
key={tag.id}
className="h-7 w-full justify-start text-xs cursor-pointer flex items-center px-2 rounded hover:bg-gray-100"
onClick={() => {
onAddTag?.(tag.name);
setShowPopover(false);
}}
>
<PlusOutlined className="w-3 h-3 mr-1" />
{tag.name}
</span>
))}
</div>
</div>
) : (
<Empty description="没有可用标签,请先创建标签。" />
)}
{/* Create New Tag */}
<div className="space-y-2 border-t border-gray-100 pt-3">
<h5 className="text-sm"></h5>
<div className="flex gap-2">
<Input
placeholder="输入新标签名称..."
value={newTag}
onChange={(e) => setNewTag(e.target.value)}
className="h-8 text-sm"
/>
<Button
onClick={() => handleCreateAndAddTag()}
disabled={!newTag.trim()}
type="primary"
>
</Button>
</div>
</div>
<Button block onClick={() => setShowPopover(false)}>
</Button>
</div>
}
>
<Tag
style={tagPlusStyle}
icon={<PlusOutlined />}
className="cursor-pointer"
onClick={() => setShowPopover(true)}
>
</Tag>
</Popover>
</>
);
}
import { Button, Input, Popover, theme, Tag, Empty } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useEffect, useMemo, useState } from "react";
interface Tag {
id: number;
name: string;
color: string;
}
interface AddTagPopoverProps {
tags: Tag[];
onFetchTags?: () => Promise<Tag[]>;
onAddTag?: (tag: Tag) => void;
onCreateAndTag?: (tagName: string) => void;
}
export default function AddTagPopover({
tags,
onFetchTags,
onAddTag,
onCreateAndTag,
}: AddTagPopoverProps) {
const { token } = theme.useToken();
const [showPopover, setShowPopover] = useState(false);
const [newTag, setNewTag] = useState("");
const [allTags, setAllTags] = useState<Tag[]>([]);
const tagsSet = useMemo(() => new Set(tags.map((tag) => tag.id)), [tags]);
const fetchTags = async () => {
if (onFetchTags && showPopover) {
const data = await onFetchTags?.();
setAllTags(data || []);
}
};
useEffect(() => {
fetchTags();
}, [showPopover]);
const availableTags = useMemo(() => {
return allTags.filter((tag) => !tagsSet.has(tag.id));
}, [allTags, tagsSet]);
const handleCreateAndAddTag = () => {
if (newTag.trim()) {
onCreateAndTag?.(newTag.trim());
setNewTag("");
}
setShowPopover(false);
};
const tagPlusStyle: React.CSSProperties = {
height: 22,
background: token.colorBgContainer,
borderStyle: "dashed",
};
return (
<>
<Popover
open={showPopover}
trigger="click"
placement="bottom"
onOpenChange={setShowPopover}
content={
<div className="space-y-4 w-[300px]">
<h4 className="font-medium border-b pb-2 border-gray-100">
</h4>
{/* Available Tags */}
{availableTags?.length ? (
<div className="space-y-2">
<h5 className="text-sm"></h5>
<div className="max-h-32 overflow-y-auto space-y-1">
{availableTags.map((tag) => (
<span
key={tag.id}
className="h-7 w-full justify-start text-xs cursor-pointer flex items-center px-2 rounded hover:bg-gray-100"
onClick={() => {
onAddTag?.(tag.name);
setShowPopover(false);
}}
>
<PlusOutlined className="w-3 h-3 mr-1" />
{tag.name}
</span>
))}
</div>
</div>
) : (
<Empty description="没有可用标签,请先创建标签。" />
)}
{/* Create New Tag */}
<div className="space-y-2 border-t border-gray-100 pt-3">
<h5 className="text-sm"></h5>
<div className="flex gap-2">
<Input
placeholder="输入新标签名称..."
value={newTag}
onChange={(e) => setNewTag(e.target.value)}
className="h-8 text-sm"
/>
<Button
onClick={() => handleCreateAndAddTag()}
disabled={!newTag.trim()}
type="primary"
>
</Button>
</div>
</div>
<Button block onClick={() => setShowPopover(false)}>
</Button>
</div>
}
>
<Tag
style={tagPlusStyle}
icon={<PlusOutlined />}
className="cursor-pointer"
onClick={() => setShowPopover(true)}
>
</Tag>
</Popover>
</>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,292 +1,292 @@
import React, { useState, useEffect, useRef } from "react";
import { Tag, Pagination, Tooltip, Empty, Popover, Spin } from "antd";
import { ClockCircleOutlined, StarFilled } from "@ant-design/icons";
import type { ItemType } from "antd/es/menu/interface";
import { formatDateTime } from "@/utils/unit";
import ActionDropdown from "./ActionDropdown";
import { Database } from "lucide-react";
interface BaseCardDataType {
id: string | number;
name: string;
type: string;
icon?: React.JSX.Element;
iconColor?: string;
status: {
label: string;
icon?: React.JSX.Element;
color?: string;
} | null;
description: string;
tags?: string[];
statistics?: { label: string; value: string | number }[];
updatedAt?: string;
}
interface CardViewProps<T> {
data: T[];
pagination: {
[key: string]: any;
current: number;
pageSize: number;
total: number;
};
operations:
| {
key: string;
label: string;
danger?: boolean;
icon?: React.JSX.Element;
onClick?: (item: T) => void;
}[]
| ((item: T) => ItemType[]);
loading?: boolean;
onView?: (item: T) => void;
onFavorite?: (item: T) => void;
isFavorite?: (item: T) => boolean;
}
// 标签渲染组件
const TagsRenderer = ({ tags }: { tags?: any[] }) => {
const [visibleTags, setVisibleTags] = useState<any[]>([]);
const [hiddenTags, setHiddenTags] = useState<any[]>([]);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!tags || tags.length === 0) return;
const calculateVisibleTags = () => {
if (!containerRef.current) return;
const containerWidth = containerRef.current.offsetWidth;
const tempDiv = document.createElement("div");
tempDiv.style.visibility = "hidden";
tempDiv.style.position = "absolute";
tempDiv.style.top = "-9999px";
tempDiv.className = "flex flex-wrap gap-1";
document.body.appendChild(tempDiv);
let totalWidth = 0;
let visibleCount = 0;
const tagElements: HTMLElement[] = [];
// 为每个tag创建临时元素来测量宽度
tags.forEach((tag, index) => {
const tagElement = document.createElement("span");
tagElement.className = "ant-tag ant-tag-default";
tagElement.style.margin = "2px";
tagElement.textContent = typeof tag === "string" ? tag : tag.name;
tempDiv.appendChild(tagElement);
tagElements.push(tagElement);
const tagWidth = tagElement.offsetWidth + 4; // 加上gap的宽度
// 如果不是最后一个标签,需要预留+n标签的空间
const plusTagWidth = index < tags.length - 1 ? 35 : 0; // +n标签大约35px宽度
if (totalWidth + tagWidth + plusTagWidth <= containerWidth) {
totalWidth += tagWidth;
visibleCount++;
} else {
// 如果当前标签放不下,且已经有可见标签,则停止
if (visibleCount > 0) return;
// 如果是第一个标签就放不下,至少显示一个
if (index === 0) {
totalWidth += tagWidth;
visibleCount = 1;
}
}
});
document.body.removeChild(tempDiv);
setVisibleTags(tags.slice(0, visibleCount));
setHiddenTags(tags.slice(visibleCount));
};
// 延迟执行以确保DOM已渲染
const timer = setTimeout(calculateVisibleTags, 0);
// 监听窗口大小变化
const handleResize = () => {
calculateVisibleTags();
};
window.addEventListener("resize", handleResize);
return () => {
clearTimeout(timer);
window.removeEventListener("resize", handleResize);
};
}, [tags]);
if (!tags || tags.length === 0) return null;
const popoverContent = (
<div className="max-w-xs">
<div className="flex flex-wrap gap-1">
{hiddenTags.map((tag, index) => (
<Tag key={index}>{typeof tag === "string" ? tag : tag.name}</Tag>
))}
</div>
</div>
);
return (
<div ref={containerRef} className="flex flex-wrap gap-1 w-full">
{visibleTags.map((tag, index) => (
<Tag key={index}>{typeof tag === "string" ? tag : tag.name}</Tag>
))}
{hiddenTags.length > 0 && (
<Popover
content={popoverContent}
title="更多标签"
trigger="hover"
placement="topLeft"
>
<Tag className="cursor-pointer bg-gray-100 border-gray-300 text-gray-600 hover:bg-gray-200">
+{hiddenTags.length}
</Tag>
</Popover>
)}
</div>
);
};
function CardView<T extends BaseCardDataType>(props: CardViewProps<T>) {
const {
data,
pagination,
operations,
loading,
onView,
onFavorite,
isFavorite,
} = props;
if (data.length === 0) {
return (
<div className="flex flex-col items-center justify-center h-full text-gray-500">
<Empty />
</div>
);
}
const ops = (item) =>
typeof operations === "function" ? operations(item) : operations;
return (
<div className="flex-overflow-hidden">
<div className="overflow-auto grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4">
{data.map((item) => (
<div
key={item.id}
className="border-card p-4 bg-white hover:shadow-lg transition-shadow duration-200"
>
<div className="flex flex-col space-y-4 h-full">
<div
className="flex flex-col space-y-4 h-full"
onClick={() => onView?.(item)}
style={{ cursor: onView ? "pointer" : "default" }}
>
{/* Header */}
<div className="flex items-start justify-between">
<div className="flex items-center gap-3 min-w-0">
{item?.icon && (
<div
className={`flex-shrink-0 w-12 h-12 bg-gradient-to-br from-sky-300 to-blue-500 text-white rounded-lg flex items-center justify-center`}
>
<div className="w-6 h-6 text-gray-50">{item?.icon}</div>
</div>
)}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h3
className={`text-base flex-1 text-ellipsis overflow-hidden whitespace-nowrap font-semibold text-gray-900 truncate`}
>
{item?.name}
</h3>
{item?.status && (
<Tag color={item?.status?.color}>
<div className="flex items-center gap-2 text-xs py-0.5">
{item?.status?.icon && (
<span>{item?.status?.icon}</span>
)}
<span>{item?.status?.label}</span>
</div>
</Tag>
)}
</div>
</div>
</div>
{onFavorite && (
<StarFilled
style={{
fontSize: "16px",
color: isFavorite?.(item) ? "#ffcc00ff" : "#d1d5db",
cursor: "pointer",
}}
onClick={() => onFavorite?.(item)}
/>
)}
</div>
<div className="flex-1 flex flex-col justify-end">
{/* Tags */}
<TagsRenderer tags={item?.tags || []} />
{/* Description */}
<p className="text-gray-600 text-xs text-ellipsis overflow-hidden whitespace-nowrap text-xs line-clamp-2 mt-2">
<Tooltip title={item?.description}>
{item?.description}
</Tooltip>
</p>
{/* Statistics */}
<div className="grid grid-cols-2 gap-4 py-3">
{item?.statistics?.map((stat, idx) => (
<div key={idx}>
<div className="text-sm text-gray-500 overflow-hidden whitespace-nowrap text-ellipsis w-full">
{stat?.label}:
</div>
<div className="text-base font-semibold text-gray-900 overflow-hidden whitespace-nowrap text-ellipsis w-full">
{stat?.value}
</div>
</div>
))}
</div>
</div>
</div>
{/* Actions */}
<div className="flex items-center justify-between pt-3 border-t border-t-gray-200">
<div className=" text-gray-500 text-right">
<div className="flex items-center gap-1">
<ClockCircleOutlined className="w-4 h-4" />{" "}
{formatDateTime(item?.updatedAt)}
</div>
</div>
{operations && (
<ActionDropdown
actions={ops(item)}
onAction={(key) => {
const operation = ops(item).find((op) => op.key === key);
if (operation?.onClick) {
operation.onClick(item);
}
}}
/>
)}
</div>
</div>
</div>
))}
</div>
<div className="flex justify-end mt-6">
<Pagination {...pagination} />
</div>
</div>
);
}
export default CardView;
import React, { useState, useEffect, useRef } from "react";
import { Tag, Pagination, Tooltip, Empty, Popover, Spin } from "antd";
import { ClockCircleOutlined, StarFilled } from "@ant-design/icons";
import type { ItemType } from "antd/es/menu/interface";
import { formatDateTime } from "@/utils/unit";
import ActionDropdown from "./ActionDropdown";
import { Database } from "lucide-react";
interface BaseCardDataType {
id: string | number;
name: string;
type: string;
icon?: React.JSX.Element;
iconColor?: string;
status: {
label: string;
icon?: React.JSX.Element;
color?: string;
} | null;
description: string;
tags?: string[];
statistics?: { label: string; value: string | number }[];
updatedAt?: string;
}
interface CardViewProps<T> {
data: T[];
pagination: {
[key: string]: any;
current: number;
pageSize: number;
total: number;
};
operations:
| {
key: string;
label: string;
danger?: boolean;
icon?: React.JSX.Element;
onClick?: (item: T) => void;
}[]
| ((item: T) => ItemType[]);
loading?: boolean;
onView?: (item: T) => void;
onFavorite?: (item: T) => void;
isFavorite?: (item: T) => boolean;
}
// 标签渲染组件
const TagsRenderer = ({ tags }: { tags?: any[] }) => {
const [visibleTags, setVisibleTags] = useState<any[]>([]);
const [hiddenTags, setHiddenTags] = useState<any[]>([]);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!tags || tags.length === 0) return;
const calculateVisibleTags = () => {
if (!containerRef.current) return;
const containerWidth = containerRef.current.offsetWidth;
const tempDiv = document.createElement("div");
tempDiv.style.visibility = "hidden";
tempDiv.style.position = "absolute";
tempDiv.style.top = "-9999px";
tempDiv.className = "flex flex-wrap gap-1";
document.body.appendChild(tempDiv);
let totalWidth = 0;
let visibleCount = 0;
const tagElements: HTMLElement[] = [];
// 为每个tag创建临时元素来测量宽度
tags.forEach((tag, index) => {
const tagElement = document.createElement("span");
tagElement.className = "ant-tag ant-tag-default";
tagElement.style.margin = "2px";
tagElement.textContent = typeof tag === "string" ? tag : tag.name;
tempDiv.appendChild(tagElement);
tagElements.push(tagElement);
const tagWidth = tagElement.offsetWidth + 4; // 加上gap的宽度
// 如果不是最后一个标签,需要预留+n标签的空间
const plusTagWidth = index < tags.length - 1 ? 35 : 0; // +n标签大约35px宽度
if (totalWidth + tagWidth + plusTagWidth <= containerWidth) {
totalWidth += tagWidth;
visibleCount++;
} else {
// 如果当前标签放不下,且已经有可见标签,则停止
if (visibleCount > 0) return;
// 如果是第一个标签就放不下,至少显示一个
if (index === 0) {
totalWidth += tagWidth;
visibleCount = 1;
}
}
});
document.body.removeChild(tempDiv);
setVisibleTags(tags.slice(0, visibleCount));
setHiddenTags(tags.slice(visibleCount));
};
// 延迟执行以确保DOM已渲染
const timer = setTimeout(calculateVisibleTags, 0);
// 监听窗口大小变化
const handleResize = () => {
calculateVisibleTags();
};
window.addEventListener("resize", handleResize);
return () => {
clearTimeout(timer);
window.removeEventListener("resize", handleResize);
};
}, [tags]);
if (!tags || tags.length === 0) return null;
const popoverContent = (
<div className="max-w-xs">
<div className="flex flex-wrap gap-1">
{hiddenTags.map((tag, index) => (
<Tag key={index}>{typeof tag === "string" ? tag : tag.name}</Tag>
))}
</div>
</div>
);
return (
<div ref={containerRef} className="flex flex-wrap gap-1 w-full">
{visibleTags.map((tag, index) => (
<Tag key={index}>{typeof tag === "string" ? tag : tag.name}</Tag>
))}
{hiddenTags.length > 0 && (
<Popover
content={popoverContent}
title="更多标签"
trigger="hover"
placement="topLeft"
>
<Tag className="cursor-pointer bg-gray-100 border-gray-300 text-gray-600 hover:bg-gray-200">
+{hiddenTags.length}
</Tag>
</Popover>
)}
</div>
);
};
function CardView<T extends BaseCardDataType>(props: CardViewProps<T>) {
const {
data,
pagination,
operations,
loading,
onView,
onFavorite,
isFavorite,
} = props;
if (data.length === 0) {
return (
<div className="flex flex-col items-center justify-center h-full text-gray-500">
<Empty />
</div>
);
}
const ops = (item) =>
typeof operations === "function" ? operations(item) : operations;
return (
<div className="flex-overflow-hidden">
<div className="overflow-auto grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4">
{data.map((item) => (
<div
key={item.id}
className="border-card p-4 bg-white hover:shadow-lg transition-shadow duration-200"
>
<div className="flex flex-col space-y-4 h-full">
<div
className="flex flex-col space-y-4 h-full"
onClick={() => onView?.(item)}
style={{ cursor: onView ? "pointer" : "default" }}
>
{/* Header */}
<div className="flex items-start justify-between">
<div className="flex items-center gap-3 min-w-0">
{item?.icon && (
<div
className={`flex-shrink-0 w-12 h-12 bg-gradient-to-br from-sky-300 to-blue-500 text-white rounded-lg flex items-center justify-center`}
>
<div className="w-6 h-6 text-gray-50">{item?.icon}</div>
</div>
)}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h3
className={`text-base flex-1 text-ellipsis overflow-hidden whitespace-nowrap font-semibold text-gray-900 truncate`}
>
{item?.name}
</h3>
{item?.status && (
<Tag color={item?.status?.color}>
<div className="flex items-center gap-2 text-xs py-0.5">
{item?.status?.icon && (
<span>{item?.status?.icon}</span>
)}
<span>{item?.status?.label}</span>
</div>
</Tag>
)}
</div>
</div>
</div>
{onFavorite && (
<StarFilled
style={{
fontSize: "16px",
color: isFavorite?.(item) ? "#ffcc00ff" : "#d1d5db",
cursor: "pointer",
}}
onClick={() => onFavorite?.(item)}
/>
)}
</div>
<div className="flex-1 flex flex-col justify-end">
{/* Tags */}
<TagsRenderer tags={item?.tags || []} />
{/* Description */}
<p className="text-gray-600 text-xs text-ellipsis overflow-hidden whitespace-nowrap text-xs line-clamp-2 mt-2">
<Tooltip title={item?.description}>
{item?.description}
</Tooltip>
</p>
{/* Statistics */}
<div className="grid grid-cols-2 gap-4 py-3">
{item?.statistics?.map((stat, idx) => (
<div key={idx}>
<div className="text-sm text-gray-500 overflow-hidden whitespace-nowrap text-ellipsis w-full">
{stat?.label}:
</div>
<div className="text-base font-semibold text-gray-900 overflow-hidden whitespace-nowrap text-ellipsis w-full">
{stat?.value}
</div>
</div>
))}
</div>
</div>
</div>
{/* Actions */}
<div className="flex items-center justify-between pt-3 border-t border-t-gray-200">
<div className=" text-gray-500 text-right">
<div className="flex items-center gap-1">
<ClockCircleOutlined className="w-4 h-4" />{" "}
{formatDateTime(item?.updatedAt)}
</div>
</div>
{operations && (
<ActionDropdown
actions={ops(item)}
onAction={(key) => {
const operation = ops(item).find((op) => op.key === key);
if (operation?.onClick) {
operation.onClick(item);
}
}}
/>
)}
</div>
</div>
</div>
))}
</div>
<div className="flex justify-end mt-6">
<Pagination {...pagination} />
</div>
</div>
);
}
export default CardView;

View File

@@ -1,145 +1,145 @@
import React from "react";
import { Database } from "lucide-react";
import { Card, Button, Tag, Tooltip, Popconfirm } from "antd";
import type { ItemType } from "antd/es/menu/interface";
import AddTagPopover from "./AddTagPopover";
import ActionDropdown from "./ActionDropdown";
interface StatisticItem {
icon: React.ReactNode;
label: string;
value: string | number;
}
interface OperationItem {
key: string;
label: string;
icon?: React.ReactNode;
isDropdown?: boolean;
items?: ItemType[];
onMenuClick?: (key: string) => void;
onClick?: () => void;
danger?: boolean;
}
interface TagConfig {
showAdd: boolean;
tags: { id: number; name: string; color: string }[];
onFetchTags?: () => Promise<{
data: { id: number; name: string; color: string }[];
}>;
onAddTag?: (tag: { id: number; name: string; color: string }) => void;
onCreateAndTag?: (tagName: string) => void;
}
interface DetailHeaderProps<T> {
data: T;
statistics: StatisticItem[];
operations: OperationItem[];
tagConfig?: TagConfig;
}
function DetailHeader<T>({
data = {} as T,
statistics,
operations,
tagConfig,
}: DetailHeaderProps<T>): React.ReactNode {
return (
<Card>
<div className="flex items-start justify-between">
<div className="flex items-start gap-4 flex-1">
<div
className={`w-16 h-16 text-white rounded-lg flex-center shadow-lg bg-gradient-to-br from-sky-300 to-blue-500 text-white`}
>
{<div className="w-8 h-8 text-gray-50">{data?.icon}</div> || (
<Database className="w-8 h-8 text-white" />
)}
</div>
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<h1 className="text-lg font-bold text-gray-900">{data?.name}</h1>
{data?.status && (
<Tag color={data.status?.color}>
<div className="flex items-center gap-2 text-xs">
{data.status?.icon && <span>{data.status?.icon}</span>}
<span>{data.status?.label}</span>
</div>
</Tag>
)}
</div>
{data?.tags && (
<div className="flex flex-wrap mb-2">
{data?.tags?.map((tag) => (
<Tag key={tag.id} className="mr-1">
{tag.name}
</Tag>
))}
{tagConfig?.showAdd && (
<AddTagPopover
tags={tagConfig.tags}
onFetchTags={tagConfig.onFetchTags}
onAddTag={tagConfig.onAddTag}
onCreateAndTag={tagConfig.onCreateAndTag}
/>
)}
</div>
)}
<p className="text-gray-700 mb-4">{data?.description}</p>
<div className="flex items-center gap-6 text-sm">
{statistics.map((stat) => (
<div key={stat.key} className="flex items-center gap-1">
{stat.icon}
<span>{stat.value}</span>
</div>
))}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{operations.map((op) => {
if (op.isDropdown) {
return (
<ActionDropdown
actions={op?.items}
onAction={op?.onMenuClick}
/>
);
}
if (op.confirm) {
return (
<Tooltip key={op.key} title={op.label}>
<Popconfirm
key={op.key}
{...op.confirm}
onConfirm={() => {
if (op.onClick) {
op.onClick()
} else {
op?.confirm?.onConfirm?.();
}
}}
okType={op.danger ? "danger" : "primary"}
overlayStyle={{ zIndex: 9999 }}
>
<Button icon={op.icon} danger={op.danger} />
</Popconfirm>
</Tooltip>
);
}
return (
<Tooltip key={op.key} title={op.label}>
<Button
icon={op.icon}
danger={op.danger}
onClick={op.onClick}
/>
</Tooltip>
);
})}
</div>
</div>
</Card>
);
}
export default DetailHeader;
import React from "react";
import { Database } from "lucide-react";
import { Card, Button, Tag, Tooltip, Popconfirm } from "antd";
import type { ItemType } from "antd/es/menu/interface";
import AddTagPopover from "./AddTagPopover";
import ActionDropdown from "./ActionDropdown";
interface StatisticItem {
icon: React.ReactNode;
label: string;
value: string | number;
}
interface OperationItem {
key: string;
label: string;
icon?: React.ReactNode;
isDropdown?: boolean;
items?: ItemType[];
onMenuClick?: (key: string) => void;
onClick?: () => void;
danger?: boolean;
}
interface TagConfig {
showAdd: boolean;
tags: { id: number; name: string; color: string }[];
onFetchTags?: () => Promise<{
data: { id: number; name: string; color: string }[];
}>;
onAddTag?: (tag: { id: number; name: string; color: string }) => void;
onCreateAndTag?: (tagName: string) => void;
}
interface DetailHeaderProps<T> {
data: T;
statistics: StatisticItem[];
operations: OperationItem[];
tagConfig?: TagConfig;
}
function DetailHeader<T>({
data = {} as T,
statistics,
operations,
tagConfig,
}: DetailHeaderProps<T>): React.ReactNode {
return (
<Card>
<div className="flex items-start justify-between">
<div className="flex items-start gap-4 flex-1">
<div
className={`w-16 h-16 text-white rounded-lg flex-center shadow-lg bg-gradient-to-br from-sky-300 to-blue-500 text-white`}
>
{<div className="w-8 h-8 text-gray-50">{data?.icon}</div> || (
<Database className="w-8 h-8 text-white" />
)}
</div>
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<h1 className="text-lg font-bold text-gray-900">{data?.name}</h1>
{data?.status && (
<Tag color={data.status?.color}>
<div className="flex items-center gap-2 text-xs">
{data.status?.icon && <span>{data.status?.icon}</span>}
<span>{data.status?.label}</span>
</div>
</Tag>
)}
</div>
{data?.tags && (
<div className="flex flex-wrap mb-2">
{data?.tags?.map((tag) => (
<Tag key={tag.id} className="mr-1">
{tag.name}
</Tag>
))}
{tagConfig?.showAdd && (
<AddTagPopover
tags={tagConfig.tags}
onFetchTags={tagConfig.onFetchTags}
onAddTag={tagConfig.onAddTag}
onCreateAndTag={tagConfig.onCreateAndTag}
/>
)}
</div>
)}
<p className="text-gray-700 mb-4">{data?.description}</p>
<div className="flex items-center gap-6 text-sm">
{statistics.map((stat) => (
<div key={stat.key} className="flex items-center gap-1">
{stat.icon}
<span>{stat.value}</span>
</div>
))}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{operations.map((op) => {
if (op.isDropdown) {
return (
<ActionDropdown
actions={op?.items}
onAction={op?.onMenuClick}
/>
);
}
if (op.confirm) {
return (
<Tooltip key={op.key} title={op.label}>
<Popconfirm
key={op.key}
{...op.confirm}
onConfirm={() => {
if (op.onClick) {
op.onClick()
} else {
op?.confirm?.onConfirm?.();
}
}}
okType={op.danger ? "danger" : "primary"}
overlayStyle={{ zIndex: 9999 }}
>
<Button icon={op.icon} danger={op.danger} />
</Popconfirm>
</Tooltip>
);
}
return (
<Tooltip key={op.key} title={op.label}>
<Button
icon={op.icon}
danger={op.danger}
onClick={op.onClick}
/>
</Tooltip>
);
})}
</div>
</div>
</Card>
);
}
export default DetailHeader;

View File

@@ -1,28 +1,28 @@
import { Button } from "antd";
const DevelopmentInProgress = ({ showHome = true, showTime = "" }) => {
return (
<div className="mt-40 flex flex-col items-center justify-center">
<div className="hero-icon">🚧</div>
<h1 className="text-2xl font-bold"></h1>
{showTime && (
<p className="mt-4">
<b>{showTime}</b>
</p>
)}
{showHome && (
<Button
type="primary"
className="mt-6"
onClick={() => {
window.location.href = "/";
}}
>
</Button>
)}
</div>
);
};
export default DevelopmentInProgress;
import { Button } from "antd";
const DevelopmentInProgress = ({ showHome = true, showTime = "" }) => {
return (
<div className="mt-40 flex flex-col items-center justify-center">
<div className="hero-icon">🚧</div>
<h1 className="text-2xl font-bold"></h1>
{showTime && (
<p className="mt-4">
<b>{showTime}</b>
</p>
)}
{showHome && (
<Button
type="primary"
className="mt-6"
onClick={() => {
window.location.href = "/";
}}
>
</Button>
)}
</div>
);
};
export default DevelopmentInProgress;

View File

@@ -1,191 +1,191 @@
import React, { Component } from "react";
import { Button, Modal } from "antd";
interface ErrorContextType {
hasError: boolean;
error: Error | null;
errorInfo: { componentStack: string } | null;
}
const ErrorContext = React.createContext<ErrorContextType>({
hasError: false,
error: null,
errorInfo: null,
});
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: { componentStack: string } | null;
errorTimestamp: string | null;
}
interface ErrorBoundaryProps {
children?: React.ReactNode;
onReset?: () => void;
showDetails?: boolean;
}
export default class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
errorTimestamp: null,
};
}
static getDerivedStateFromError(error: any) {
// 更新 state 使下一次渲染能够显示降级 UI
return {
hasError: true,
error: error,
errorTimestamp: new Date().toISOString(),
};
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
// 错误统计
this.setState({
error,
errorInfo,
hasError: true,
});
// 在实际应用中,这里可以集成错误报告服务
this.logErrorToService(error, errorInfo);
// 开发环境下在控制台显示详细错误
if (process.env.NODE_ENV === "development") {
console.error("ErrorBoundary 捕获到错误:", error);
console.error("错误详情:", errorInfo);
}
}
logErrorToService = (error: Error, errorInfo: React.ErrorInfo) => {
// 这里可以集成 Sentry、LogRocket 等错误监控服务
const errorData = {
error: error.toString(),
errorInfo: errorInfo.componentStack,
timestamp: this.state.errorTimestamp,
url: window.location.href,
userAgent: navigator.userAgent,
};
// 模拟发送错误日志
console.log("发送错误日志到监控服务:", errorData);
// 实际使用时取消注释并配置您的错误监控服务
/*
if (window.Sentry) {
window.Sentry.captureException(error, { extra: errorInfo });
}
*/
};
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
errorTimestamp: null,
});
// 可选:重新加载页面或执行其他恢复操作
if (this.props.onReset) {
this.props.onReset();
}
};
handleReload = () => {
window.location.reload();
};
handleGoHome = () => {
window.location.href = "/";
};
renderErrorDetails = () => {
const { error, errorInfo } = this.state;
if (!this.props.showDetails) return null;
return (
<div className="bg-gray-100 p-4 mt-4 text-left rounded">
<div className="mt-2">
<strong>:</strong>
<pre className="bg-gray-600 px-4 py-2 rounded text-white overflow-auto">
{error?.toString()}
</pre>
</div>
{errorInfo && (
<div className="mt-2">
<strong>:</strong>
<pre className="bg-gray-600 max-h-100 px-4 py-2 rounded text-white overflow-auto">
{errorInfo.componentStack}
</pre>
</div>
)}
</div>
);
};
render() {
if (this.state.hasError) {
return (
<Modal visible width={1000} footer={null} closable={false}>
<div className="text-center p-6">
<div className="text-3xl"></div>
<h1 className="text-xl p-2"></h1>
<p className="text-sm text-gray-400"></p>
<div className="flex justify-center gap-4 my-4">
<Button onClick={this.handleReload}></Button>
<Button type="primary" onClick={this.handleGoHome}>
</Button>
</div>
{this.renderErrorDetails()}
<div className="mt-4 border-t border-gray-100 pt-4 text-center">
<p className="text-sm text-gray-500">
</p>
<small className="text-xs text-gray-400">
ID: {this.state.errorTimestamp}
</small>
</div>
</div>
</Modal>
);
}
return (
<ErrorContext.Provider
value={{
hasError: this.state.hasError,
error: this.state.error,
errorInfo: this.state.errorInfo,
}}
>
{this.props.children}
</ErrorContext.Provider>
);
}
}
export function withErrorBoundary(
Component: React.ComponentType
): React.ComponentType {
return (props) => (
<ErrorBoundary showDetails={process.env.NODE_ENV === "development"}>
<Component {...props} />
</ErrorBoundary>
);
}
import React, { Component } from "react";
import { Button, Modal } from "antd";
interface ErrorContextType {
hasError: boolean;
error: Error | null;
errorInfo: { componentStack: string } | null;
}
const ErrorContext = React.createContext<ErrorContextType>({
hasError: false,
error: null,
errorInfo: null,
});
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: { componentStack: string } | null;
errorTimestamp: string | null;
}
interface ErrorBoundaryProps {
children?: React.ReactNode;
onReset?: () => void;
showDetails?: boolean;
}
export default class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
errorTimestamp: null,
};
}
static getDerivedStateFromError(error: any) {
// 更新 state 使下一次渲染能够显示降级 UI
return {
hasError: true,
error: error,
errorTimestamp: new Date().toISOString(),
};
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
// 错误统计
this.setState({
error,
errorInfo,
hasError: true,
});
// 在实际应用中,这里可以集成错误报告服务
this.logErrorToService(error, errorInfo);
// 开发环境下在控制台显示详细错误
if (process.env.NODE_ENV === "development") {
console.error("ErrorBoundary 捕获到错误:", error);
console.error("错误详情:", errorInfo);
}
}
logErrorToService = (error: Error, errorInfo: React.ErrorInfo) => {
// 这里可以集成 Sentry、LogRocket 等错误监控服务
const errorData = {
error: error.toString(),
errorInfo: errorInfo.componentStack,
timestamp: this.state.errorTimestamp,
url: window.location.href,
userAgent: navigator.userAgent,
};
// 模拟发送错误日志
console.log("发送错误日志到监控服务:", errorData);
// 实际使用时取消注释并配置您的错误监控服务
/*
if (window.Sentry) {
window.Sentry.captureException(error, { extra: errorInfo });
}
*/
};
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
errorTimestamp: null,
});
// 可选:重新加载页面或执行其他恢复操作
if (this.props.onReset) {
this.props.onReset();
}
};
handleReload = () => {
window.location.reload();
};
handleGoHome = () => {
window.location.href = "/";
};
renderErrorDetails = () => {
const { error, errorInfo } = this.state;
if (!this.props.showDetails) return null;
return (
<div className="bg-gray-100 p-4 mt-4 text-left rounded">
<div className="mt-2">
<strong>:</strong>
<pre className="bg-gray-600 px-4 py-2 rounded text-white overflow-auto">
{error?.toString()}
</pre>
</div>
{errorInfo && (
<div className="mt-2">
<strong>:</strong>
<pre className="bg-gray-600 max-h-100 px-4 py-2 rounded text-white overflow-auto">
{errorInfo.componentStack}
</pre>
</div>
)}
</div>
);
};
render() {
if (this.state.hasError) {
return (
<Modal visible width={1000} footer={null} closable={false}>
<div className="text-center p-6">
<div className="text-3xl"></div>
<h1 className="text-xl p-2"></h1>
<p className="text-sm text-gray-400"></p>
<div className="flex justify-center gap-4 my-4">
<Button onClick={this.handleReload}></Button>
<Button type="primary" onClick={this.handleGoHome}>
</Button>
</div>
{this.renderErrorDetails()}
<div className="mt-4 border-t border-gray-100 pt-4 text-center">
<p className="text-sm text-gray-500">
</p>
<small className="text-xs text-gray-400">
ID: {this.state.errorTimestamp}
</small>
</div>
</div>
</Modal>
);
}
return (
<ErrorContext.Provider
value={{
hasError: this.state.hasError,
error: this.state.error,
errorInfo: this.state.errorInfo,
}}
>
{this.props.children}
</ErrorContext.Provider>
);
}
}
export function withErrorBoundary(
Component: React.ComponentType
): React.ComponentType {
return (props) => (
<ErrorBoundary showDetails={process.env.NODE_ENV === "development"}>
<Component {...props} />
</ErrorBoundary>
);
}

View File

@@ -1,70 +1,70 @@
import React from "react";
import { Card } from "antd";
interface RadioCardOption {
value: string;
label: string;
description?: string;
icon?: SVGAElement | React.FC<React.SVGProps<SVGElement>>;
color?: string;
}
interface RadioCardProps {
options: RadioCardOption[];
value: string;
onChange: (value: string) => void;
className?: string;
}
const RadioCard: React.FC<RadioCardProps> = ({
options,
value,
onChange,
className,
}) => {
return (
<div
className={`grid gap-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 ${
className || ""
}`}
style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))" }}
>
{options.map((option) => (
<div
key={option.value}
className="border-card hover:shadow-lg p-4 text-center"
style={{
borderColor: value === option.value ? "#1677ff" : undefined,
background: value === option.value ? "#e6f7ff" : undefined,
cursor: "pointer",
}}
onClick={() => onChange(option.value)}
>
<option.icon
className={`w-8 h-8 mx-auto mb-2 ${
value === option.value ? "text-blue-500" : "text-gray-400"
}`}
/>
<h3
className={`font-medium text-sm mb-1 ${
value === option.value ? "text-blue-500" : "text-gray-900"
}`}
>
{option.label}
</h3>
{option.description && (
<div
className={`text-xs ${
value === option.value ? "text-blue-500" : "text-gray-500"
}`}
>
{option.description}
</div>
)}
</div>
))}
</div>
);
};
export default RadioCard;
import React from "react";
import { Card } from "antd";
interface RadioCardOption {
value: string;
label: string;
description?: string;
icon?: SVGAElement | React.FC<React.SVGProps<SVGElement>>;
color?: string;
}
interface RadioCardProps {
options: RadioCardOption[];
value: string;
onChange: (value: string) => void;
className?: string;
}
const RadioCard: React.FC<RadioCardProps> = ({
options,
value,
onChange,
className,
}) => {
return (
<div
className={`grid gap-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 ${
className || ""
}`}
style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))" }}
>
{options.map((option) => (
<div
key={option.value}
className="border-card hover:shadow-lg p-4 text-center"
style={{
borderColor: value === option.value ? "#1677ff" : undefined,
background: value === option.value ? "#e6f7ff" : undefined,
cursor: "pointer",
}}
onClick={() => onChange(option.value)}
>
<option.icon
className={`w-8 h-8 mx-auto mb-2 ${
value === option.value ? "text-blue-500" : "text-gray-400"
}`}
/>
<h3
className={`font-medium text-sm mb-1 ${
value === option.value ? "text-blue-500" : "text-gray-900"
}`}
>
{option.label}
</h3>
{option.description && (
<div
className={`text-xs ${
value === option.value ? "text-blue-500" : "text-gray-500"
}`}
>
{option.description}
</div>
)}
</div>
))}
</div>
);
};
export default RadioCard;

View File

@@ -1,239 +1,239 @@
import { Input, Button, Select, Tag, Segmented, DatePicker } from "antd";
import {
BarsOutlined,
AppstoreOutlined,
SearchOutlined,
ReloadOutlined,
} from "@ant-design/icons";
import { useEffect, useState } from "react";
interface FilterOption {
key: string;
label: string;
mode?: "tags" | "multiple";
options: { label: string; value: string }[];
}
interface SearchControlsProps {
searchTerm: string;
onSearchChange: (value: string) => void;
searchPlaceholder?: string;
// Filter props
filters?: FilterOption[];
selectedFilters?: Record<string, string[]>;
onFiltersChange?: (filters: Record<string, string[]>) => void;
onClearFilters?: () => void;
// Date range props
dateRange?: [Date | null, Date | null] | null;
onDateChange?: (dates: [Date | null, Date | null] | null) => void;
// Reload props
onReload?: () => void;
// View props
viewMode?: "card" | "list";
onViewModeChange?: (mode: "card" | "list") => void;
// Control visibility
showFilters?: boolean;
showSort?: boolean;
showViewToggle?: boolean;
showReload?: boolean;
showDatePicker?: boolean;
// Styling
className?: string;
}
export function SearchControls({
viewMode,
className,
searchTerm,
showFilters = true,
showViewToggle = true,
searchPlaceholder = "搜索...",
filters = [],
dateRange,
showDatePicker = false,
showReload = true,
onReload,
onDateChange,
onSearchChange,
onFiltersChange,
onViewModeChange,
onClearFilters,
}: SearchControlsProps) {
const [selectedFilters, setSelectedFilters] = useState<{
[key: string]: string[];
}>({});
const filtersMap: Record<string, FilterOption> = filters.reduce(
(prev, cur) => ({ ...prev, [cur.key]: cur }),
{}
);
// select change
const handleFilterChange = (filterKey: string, value: string) => {
const filteredValues = {
...selectedFilters,
[filterKey]: !value ? [] : [value],
};
setSelectedFilters(filteredValues);
};
// 清除已选筛选
const handleClearFilter = (filterKey: string, value: string | string[]) => {
const isMultiple = filtersMap[filterKey]?.mode === "multiple";
if (!isMultiple) {
setSelectedFilters({
...selectedFilters,
[filterKey]: [],
});
} else {
const currentValues = selectedFilters[filterKey]?.[0] || [];
const newValues = currentValues.filter((v) => v !== value);
setSelectedFilters({
...selectedFilters,
[filterKey]: [newValues],
});
}
};
const handleClearAllFilters = () => {
setSelectedFilters({});
onClearFilters?.();
};
const hasActiveFilters = Object.values(selectedFilters).some(
(values) => values?.[0]?.length > 0
);
useEffect(() => {
if (Object.keys(selectedFilters).length === 0) return;
onFiltersChange?.(selectedFilters);
}, [selectedFilters]);
return (
<div className={className}>
<div className="flex items-center justify-between gap-8">
{/* Left side - Search and Filters */}
<div className="flex items-center gap-2 flex-1">
{/* Search */}
<div className="relative flex-1">
<Input
allowClear
placeholder={searchPlaceholder}
value={searchTerm}
onChange={(e) => onSearchChange(e.target.value)}
prefix={<SearchOutlined className="w-4 h-4 text-gray-400" />}
/>
</div>
{/* Filters */}
{showFilters && filters.length > 0 && (
<div className="flex items-center gap-2">
{filters.map((filter: FilterOption) => (
<Select
maxTagCount="responsive"
mode={filter.mode}
key={filter.key}
placeholder={filter.label}
value={selectedFilters[filter.key]?.[0] || undefined}
onChange={(value) => handleFilterChange(filter.key, value)}
style={{ width: 144 }}
allowClear
>
{filter.options.map((option) => (
<Select.Option key={option.value} value={option.value}>
{option.label}
</Select.Option>
))}
</Select>
))}
</div>
)}
</div>
{showDatePicker && (
<DatePicker.RangePicker
value={dateRange as any}
onChange={onDateChange}
style={{ width: 260 }}
allowClear
placeholder={["开始时间", "结束时间"]}
/>
)}
{/* Right side */}
<div className="flex items-center gap-2">
{showViewToggle && onViewModeChange && (
<Segmented
options={[
{ value: "list", icon: <BarsOutlined /> },
{ value: "card", icon: <AppstoreOutlined /> },
]}
value={viewMode}
onChange={(value) => onViewModeChange(value as "list" | "card")}
/>
)}
{showReload && (
<Button
icon={<ReloadOutlined />}
onClick={() => onReload?.()}
></Button>
)}
</div>
</div>
{/* Active Filters Display */}
{hasActiveFilters && (
<div className="mt-4 pt-4 border-t border-gray-200">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 flex-wrap flex-1">
<span className="text-sm font-medium text-gray-700">
:
</span>
{Object.entries(selectedFilters).map(([filterKey, values]) =>
values.map((value) => {
const filter = filtersMap[filterKey];
const getLabeledValue = (item: string) => {
const option = filter?.options.find(
(o) => o.value === item
);
return (
<Tag
key={`${filterKey}-${item}`}
closable
onClose={() => handleClearFilter(filterKey, item)}
color="blue"
>
{filter?.label}: {option?.label || item}
</Tag>
);
};
return Array.isArray(value)
? value.map((item) => getLabeledValue(item))
: getLabeledValue(value);
})
)}
</div>
{/* Clear all filters button on the right */}
<Button
type="text"
size="small"
onClick={handleClearAllFilters}
className="text-gray-500 hover:text-gray-700"
>
</Button>
</div>
</div>
)}
</div>
);
}
import { Input, Button, Select, Tag, Segmented, DatePicker } from "antd";
import {
BarsOutlined,
AppstoreOutlined,
SearchOutlined,
ReloadOutlined,
} from "@ant-design/icons";
import { useEffect, useState } from "react";
interface FilterOption {
key: string;
label: string;
mode?: "tags" | "multiple";
options: { label: string; value: string }[];
}
interface SearchControlsProps {
searchTerm: string;
onSearchChange: (value: string) => void;
searchPlaceholder?: string;
// Filter props
filters?: FilterOption[];
selectedFilters?: Record<string, string[]>;
onFiltersChange?: (filters: Record<string, string[]>) => void;
onClearFilters?: () => void;
// Date range props
dateRange?: [Date | null, Date | null] | null;
onDateChange?: (dates: [Date | null, Date | null] | null) => void;
// Reload props
onReload?: () => void;
// View props
viewMode?: "card" | "list";
onViewModeChange?: (mode: "card" | "list") => void;
// Control visibility
showFilters?: boolean;
showSort?: boolean;
showViewToggle?: boolean;
showReload?: boolean;
showDatePicker?: boolean;
// Styling
className?: string;
}
export function SearchControls({
viewMode,
className,
searchTerm,
showFilters = true,
showViewToggle = true,
searchPlaceholder = "搜索...",
filters = [],
dateRange,
showDatePicker = false,
showReload = true,
onReload,
onDateChange,
onSearchChange,
onFiltersChange,
onViewModeChange,
onClearFilters,
}: SearchControlsProps) {
const [selectedFilters, setSelectedFilters] = useState<{
[key: string]: string[];
}>({});
const filtersMap: Record<string, FilterOption> = filters.reduce(
(prev, cur) => ({ ...prev, [cur.key]: cur }),
{}
);
// select change
const handleFilterChange = (filterKey: string, value: string) => {
const filteredValues = {
...selectedFilters,
[filterKey]: !value ? [] : [value],
};
setSelectedFilters(filteredValues);
};
// 清除已选筛选
const handleClearFilter = (filterKey: string, value: string | string[]) => {
const isMultiple = filtersMap[filterKey]?.mode === "multiple";
if (!isMultiple) {
setSelectedFilters({
...selectedFilters,
[filterKey]: [],
});
} else {
const currentValues = selectedFilters[filterKey]?.[0] || [];
const newValues = currentValues.filter((v) => v !== value);
setSelectedFilters({
...selectedFilters,
[filterKey]: [newValues],
});
}
};
const handleClearAllFilters = () => {
setSelectedFilters({});
onClearFilters?.();
};
const hasActiveFilters = Object.values(selectedFilters).some(
(values) => values?.[0]?.length > 0
);
useEffect(() => {
if (Object.keys(selectedFilters).length === 0) return;
onFiltersChange?.(selectedFilters);
}, [selectedFilters]);
return (
<div className={className}>
<div className="flex items-center justify-between gap-8">
{/* Left side - Search and Filters */}
<div className="flex items-center gap-2 flex-1">
{/* Search */}
<div className="relative flex-1">
<Input
allowClear
placeholder={searchPlaceholder}
value={searchTerm}
onChange={(e) => onSearchChange(e.target.value)}
prefix={<SearchOutlined className="w-4 h-4 text-gray-400" />}
/>
</div>
{/* Filters */}
{showFilters && filters.length > 0 && (
<div className="flex items-center gap-2">
{filters.map((filter: FilterOption) => (
<Select
maxTagCount="responsive"
mode={filter.mode}
key={filter.key}
placeholder={filter.label}
value={selectedFilters[filter.key]?.[0] || undefined}
onChange={(value) => handleFilterChange(filter.key, value)}
style={{ width: 144 }}
allowClear
>
{filter.options.map((option) => (
<Select.Option key={option.value} value={option.value}>
{option.label}
</Select.Option>
))}
</Select>
))}
</div>
)}
</div>
{showDatePicker && (
<DatePicker.RangePicker
value={dateRange as any}
onChange={onDateChange}
style={{ width: 260 }}
allowClear
placeholder={["开始时间", "结束时间"]}
/>
)}
{/* Right side */}
<div className="flex items-center gap-2">
{showViewToggle && onViewModeChange && (
<Segmented
options={[
{ value: "list", icon: <BarsOutlined /> },
{ value: "card", icon: <AppstoreOutlined /> },
]}
value={viewMode}
onChange={(value) => onViewModeChange(value as "list" | "card")}
/>
)}
{showReload && (
<Button
icon={<ReloadOutlined />}
onClick={() => onReload?.()}
></Button>
)}
</div>
</div>
{/* Active Filters Display */}
{hasActiveFilters && (
<div className="mt-4 pt-4 border-t border-gray-200">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 flex-wrap flex-1">
<span className="text-sm font-medium text-gray-700">
:
</span>
{Object.entries(selectedFilters).map(([filterKey, values]) =>
values.map((value) => {
const filter = filtersMap[filterKey];
const getLabeledValue = (item: string) => {
const option = filter?.options.find(
(o) => o.value === item
);
return (
<Tag
key={`${filterKey}-${item}`}
closable
onClose={() => handleClearFilter(filterKey, item)}
color="blue"
>
{filter?.label}: {option?.label || item}
</Tag>
);
};
return Array.isArray(value)
? value.map((item) => getLabeledValue(item))
: getLabeledValue(value);
})
)}
</div>
{/* Clear all filters button on the right */}
<Button
type="text"
size="small"
onClick={handleClearAllFilters}
className="text-gray-500 hover:text-gray-700"
>
</Button>
</div>
</div>
)}
</div>
);
}

View File

@@ -1,149 +1,149 @@
import React, { useEffect, useRef, useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import type { InputRef } from "antd";
import { Flex, Input, Tag, theme, Tooltip } from "antd";
const tagInputStyle: React.CSSProperties = {
width: 64,
height: 22,
marginInlineEnd: 8,
verticalAlign: "top",
};
interface TagListProps {
tags: string[];
setTags: (tags: string[]) => void;
onDelete?: (tag: string) => void;
onAdd?: (tag: string) => void;
onEdit?: (oldTag: string, newTag: string) => void;
}
const TagList: React.FC<TagListProps> = ({
tags,
setTags,
onDelete,
onAdd,
onEdit,
}) => {
const { token } = theme.useToken();
const [inputVisible, setInputVisible] = useState(false);
const [inputValue, setInputValue] = useState("");
const [editInputIndex, setEditInputIndex] = useState(-1);
const [editInputValue, setEditInputValue] = useState("");
const inputRef = useRef<InputRef>(null);
const editInputRef = useRef<InputRef>(null);
useEffect(() => {
if (inputVisible) {
inputRef.current?.focus();
}
}, [inputVisible]);
useEffect(() => {
editInputRef.current?.focus();
}, [editInputValue]);
const handleClose = (removedTag: string) => {
const newTags = tags.filter((tag) => tag !== removedTag);
setTags(newTags);
onDelete?.(removedTag);
};
const showInput = () => {
setInputVisible(true);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
const handleInputConfirm = () => {
if (inputValue && !tags.includes(inputValue)) {
setTags([...tags, inputValue]);
onAdd?.(inputValue);
}
setInputVisible(false);
setInputValue("");
};
const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEditInputValue(e.target.value);
};
const handleEditInputConfirm = () => {
const newTags = [...tags];
newTags[editInputIndex] = editInputValue;
setTags(newTags);
onEdit?.(tags[editInputIndex], editInputValue);
setEditInputIndex(-1);
setEditInputValue("");
};
const tagPlusStyle: React.CSSProperties = {
height: 22,
background: token.colorBgContainer,
borderStyle: "dashed",
};
return (
<Flex gap="4px 0" wrap>
{tags.map<React.ReactNode>((tag, index) => {
if (editInputIndex === index) {
return (
<Input
ref={editInputRef}
key={tag}
size="small"
style={tagInputStyle}
value={editInputValue}
onChange={handleEditInputChange}
onBlur={handleEditInputConfirm}
onPressEnter={handleEditInputConfirm}
/>
);
}
const isLongTag = tag.length > 20;
const tagElem = (
<Tag key={tag} onClose={() => handleClose(tag)} closable>
<span
onDoubleClick={(e) => {
if (index !== 0) {
setEditInputIndex(index);
setEditInputValue(tag);
e.preventDefault();
}
}}
>
{isLongTag ? `${tag.slice(0, 20)}...` : tag}
</span>
</Tag>
);
return isLongTag ? (
<Tooltip title={tag} key={tag}>
{tagElem}
</Tooltip>
) : (
tagElem
);
})}
{inputVisible ? (
<Input
ref={inputRef}
type="text"
size="small"
style={tagInputStyle}
value={inputValue}
onChange={handleInputChange}
onBlur={handleInputConfirm}
onPressEnter={handleInputConfirm}
/>
) : (
<Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
</Tag>
)}
</Flex>
);
};
export default TagList;
import React, { useEffect, useRef, useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import type { InputRef } from "antd";
import { Flex, Input, Tag, theme, Tooltip } from "antd";
const tagInputStyle: React.CSSProperties = {
width: 64,
height: 22,
marginInlineEnd: 8,
verticalAlign: "top",
};
interface TagListProps {
tags: string[];
setTags: (tags: string[]) => void;
onDelete?: (tag: string) => void;
onAdd?: (tag: string) => void;
onEdit?: (oldTag: string, newTag: string) => void;
}
const TagList: React.FC<TagListProps> = ({
tags,
setTags,
onDelete,
onAdd,
onEdit,
}) => {
const { token } = theme.useToken();
const [inputVisible, setInputVisible] = useState(false);
const [inputValue, setInputValue] = useState("");
const [editInputIndex, setEditInputIndex] = useState(-1);
const [editInputValue, setEditInputValue] = useState("");
const inputRef = useRef<InputRef>(null);
const editInputRef = useRef<InputRef>(null);
useEffect(() => {
if (inputVisible) {
inputRef.current?.focus();
}
}, [inputVisible]);
useEffect(() => {
editInputRef.current?.focus();
}, [editInputValue]);
const handleClose = (removedTag: string) => {
const newTags = tags.filter((tag) => tag !== removedTag);
setTags(newTags);
onDelete?.(removedTag);
};
const showInput = () => {
setInputVisible(true);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
const handleInputConfirm = () => {
if (inputValue && !tags.includes(inputValue)) {
setTags([...tags, inputValue]);
onAdd?.(inputValue);
}
setInputVisible(false);
setInputValue("");
};
const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEditInputValue(e.target.value);
};
const handleEditInputConfirm = () => {
const newTags = [...tags];
newTags[editInputIndex] = editInputValue;
setTags(newTags);
onEdit?.(tags[editInputIndex], editInputValue);
setEditInputIndex(-1);
setEditInputValue("");
};
const tagPlusStyle: React.CSSProperties = {
height: 22,
background: token.colorBgContainer,
borderStyle: "dashed",
};
return (
<Flex gap="4px 0" wrap>
{tags.map<React.ReactNode>((tag, index) => {
if (editInputIndex === index) {
return (
<Input
ref={editInputRef}
key={tag}
size="small"
style={tagInputStyle}
value={editInputValue}
onChange={handleEditInputChange}
onBlur={handleEditInputConfirm}
onPressEnter={handleEditInputConfirm}
/>
);
}
const isLongTag = tag.length > 20;
const tagElem = (
<Tag key={tag} onClose={() => handleClose(tag)} closable>
<span
onDoubleClick={(e) => {
if (index !== 0) {
setEditInputIndex(index);
setEditInputValue(tag);
e.preventDefault();
}
}}
>
{isLongTag ? `${tag.slice(0, 20)}...` : tag}
</span>
</Tag>
);
return isLongTag ? (
<Tooltip title={tag} key={tag}>
{tagElem}
</Tooltip>
) : (
tagElem
);
})}
{inputVisible ? (
<Input
ref={inputRef}
type="text"
size="small"
style={tagInputStyle}
value={inputValue}
onChange={handleInputChange}
onBlur={handleInputConfirm}
onPressEnter={handleInputConfirm}
/>
) : (
<Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
</Tag>
)}
</Flex>
);
};
export default TagList;

View File

@@ -1,69 +1,69 @@
import { useEffect, useRef, useState } from "react";
const TopLoadingBar = () => {
const [isVisible, setIsVisible] = useState(false);
const [progress, setProgress] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
// 监听全局事件
const handleShow = () => {
setIsVisible(true);
setProgress(0);
// 清除可能存在的旧interval
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
// 模拟进度
let currentProgress = 0;
intervalRef.current = setInterval(() => {
currentProgress += Math.random() * 10;
if (currentProgress >= 90) {
clearInterval(intervalRef.current);
}
setProgress(currentProgress);
}, 200);
};
const handleHide = () => {
// 清除进度interval
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
setProgress(100);
setTimeout(() => {
setIsVisible(false);
setProgress(0);
}, 300);
};
// 添加全局事件监听器
window.addEventListener("loading:show", handleShow);
window.addEventListener("loading:hide", handleHide);
return () => {
// 组件卸载时清理
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
window.removeEventListener("loading:show", handleShow);
window.removeEventListener("loading:hide", handleHide);
};
}, []);
if (!isVisible) return null;
return (
<div className="top-loading-bar">
<div
className="loading-bar-progress"
style={{ width: `${progress}%` }}
></div>
</div>
);
};
export default TopLoadingBar;
import { useEffect, useRef, useState } from "react";
const TopLoadingBar = () => {
const [isVisible, setIsVisible] = useState(false);
const [progress, setProgress] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
// 监听全局事件
const handleShow = () => {
setIsVisible(true);
setProgress(0);
// 清除可能存在的旧interval
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
// 模拟进度
let currentProgress = 0;
intervalRef.current = setInterval(() => {
currentProgress += Math.random() * 10;
if (currentProgress >= 90) {
clearInterval(intervalRef.current);
}
setProgress(currentProgress);
}, 200);
};
const handleHide = () => {
// 清除进度interval
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
setProgress(100);
setTimeout(() => {
setIsVisible(false);
setProgress(0);
}, 300);
};
// 添加全局事件监听器
window.addEventListener("loading:show", handleShow);
window.addEventListener("loading:hide", handleHide);
return () => {
// 组件卸载时清理
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
window.removeEventListener("loading:show", handleShow);
window.removeEventListener("loading:hide", handleHide);
};
}, []);
if (!isVisible) return null;
return (
<div className="top-loading-bar">
<div
className="loading-bar-progress"
style={{ width: `${progress}%` }}
></div>
</div>
);
};
export default TopLoadingBar;

View File

@@ -1,331 +1,331 @@
import React, { useCallback, useEffect } from "react";
import { Button, Input, Table } from "antd";
import { RightOutlined } from "@ant-design/icons";
import { mapDataset } from "@/pages/DataManagement/dataset.const";
import {
Dataset,
DatasetFile,
DatasetType,
} from "@/pages/DataManagement/dataset.model";
import {
queryDatasetFilesUsingGet,
queryDatasetsUsingGet,
} from "@/pages/DataManagement/dataset.api";
import { formatBytes } from "@/utils/unit";
import { useDebouncedEffect } from "@/hooks/useDebouncedEffect";
interface DatasetFileTransferProps
extends React.HTMLAttributes<HTMLDivElement> {
open: boolean;
selectedFilesMap: { [key: string]: DatasetFile };
onSelectedFilesChange: (filesMap: { [key: string]: DatasetFile }) => void;
onDatasetSelect?: (dataset: Dataset | null) => void;
}
const fileCols = [
{
title: "所属数据集",
dataIndex: "datasetName",
key: "datasetName",
ellipsis: true,
},
{
title: "文件名",
dataIndex: "fileName",
key: "fileName",
ellipsis: true,
},
{
title: "大小",
dataIndex: "fileSize",
key: "fileSize",
ellipsis: true,
render: formatBytes,
},
];
// Customize Table Transfer
const DatasetFileTransfer: React.FC<DatasetFileTransferProps> = ({
open,
selectedFilesMap,
onSelectedFilesChange,
onDatasetSelect,
...props
}) => {
const [datasets, setDatasets] = React.useState<Dataset[]>([]);
const [datasetSearch, setDatasetSearch] = React.useState<string>("");
const [datasetPagination, setDatasetPagination] = React.useState<{
current: number;
pageSize: number;
total: number;
}>({ current: 1, pageSize: 10, total: 0 });
const [files, setFiles] = React.useState<DatasetFile[]>([]);
const [filesSearch, setFilesSearch] = React.useState<string>("");
const [filesPagination, setFilesPagination] = React.useState<{
current: number;
pageSize: number;
total: number;
}>({ current: 1, pageSize: 10, total: 0 });
const [showFiles, setShowFiles] = React.useState<boolean>(false);
const [selectedDataset, setSelectedDataset] = React.useState<Dataset | null>(
null
);
const [datasetSelections, setDatasetSelections] = React.useState<Dataset[]>(
[]
);
const fetchDatasets = async () => {
const { data } = await queryDatasetsUsingGet({
// Ant Design Table pagination.current is 1-based; ensure backend also receives 1-based value
page: datasetPagination.current,
size: datasetPagination.pageSize,
keyword: datasetSearch,
type: DatasetType.TEXT,
});
setDatasets(data.content.map(mapDataset) || []);
setDatasetPagination((prev) => ({
...prev,
total: data.totalElements,
}));
};
useDebouncedEffect(
() => {
fetchDatasets();
},
[datasetSearch, datasetPagination.pageSize, datasetPagination.current],
300
);
const fetchFiles = useCallback(
async (
options?: Partial<{ page: number; pageSize: number; keyword: string }>
) => {
if (!selectedDataset) return;
const page = options?.page ?? filesPagination.current;
const pageSize = options?.pageSize ?? filesPagination.pageSize;
const keyword = options?.keyword ?? filesSearch;
const { data } = await queryDatasetFilesUsingGet(selectedDataset.id, {
page,
size: pageSize,
keyword,
});
setFiles(
(data.content || []).map((item: DatasetFile) => ({
...item,
key: item.id,
datasetName: selectedDataset.name,
}))
);
setFilesPagination((prev) => ({
...prev,
current: page,
pageSize,
total: data.totalElements,
}));
},
[selectedDataset, filesPagination.current, filesPagination.pageSize, filesSearch]
);
useEffect(() => {
// 当数据集变化时,重置文件分页并拉取第一页文件,避免额外的循环请求
if (selectedDataset) {
setFilesPagination({ current: 1, pageSize: 10, total: 0 });
fetchFiles({ page: 1, pageSize: 10 }).catch(() => {});
} else {
setFiles([]);
setFilesPagination({ current: 1, pageSize: 10, total: 0 });
}
// 只在 selectedDataset 变化时触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedDataset]);
useEffect(() => {
onDatasetSelect?.(selectedDataset);
}, [selectedDataset, onDatasetSelect]);
const toggleSelectFile = (record: DatasetFile) => {
if (!selectedFilesMap[record.id]) {
onSelectedFilesChange({
...selectedFilesMap,
[record.id]: record,
});
} else {
const newSelectedFiles = { ...selectedFilesMap };
delete newSelectedFiles[record.id];
onSelectedFilesChange(newSelectedFiles);
}
};
useEffect(() => {
if (!open) {
// 重置状态
setDatasets([]);
setDatasetSearch("");
setDatasetPagination({ current: 1, pageSize: 10, total: 0 });
setFiles([]);
setFilesSearch("");
setFilesPagination({ current: 1, pageSize: 10, total: 0 });
setShowFiles(false);
setSelectedDataset(null);
setDatasetSelections([]);
onDatasetSelect?.(null);
}
}, [open, onDatasetSelect]);
const datasetCols = [
{
title: "数据集名称",
dataIndex: "name",
key: "name",
ellipsis: true,
},
{
title: "文件数",
dataIndex: "fileCount",
key: "fileCount",
ellipsis: true,
},
{
title: "大小",
dataIndex: "totalSize",
key: "totalSize",
ellipsis: true,
render: formatBytes,
},
];
return (
<div {...props}>
<div className="grid grid-cols-25 gap-4 w-full">
<div className="border-card flex flex-col col-span-12">
<div className="border-bottom p-2 font-bold"></div>
<div className="p-2">
<Input
placeholder="搜索数据集名称..."
value={datasetSearch}
allowClear
onChange={(e) => setDatasetSearch(e.target.value)}
/>
</div>
<Table
scroll={{ y: 400 }}
rowKey="id"
size="small"
rowClassName={(record) =>
selectedDataset?.id === record.id ? "bg-blue-100" : ""
}
onRow={(record: Dataset) => ({
onClick: () => {
setSelectedDataset(record);
if (!datasetSelections.find((d) => d.id === record.id)) {
setDatasetSelections([...datasetSelections, record]);
} else {
setDatasetSelections(
datasetSelections.filter((d) => d.id !== record.id)
);
}
},
})}
dataSource={datasets}
columns={datasetCols}
pagination={{
...datasetPagination,
onChange: (page, pageSize) =>
setDatasetPagination({
current: page,
pageSize: pageSize || datasetPagination.pageSize,
total: datasetPagination.total,
}),
}}
/>
</div>
<RightOutlined />
<div className="border-card flex flex-col col-span-12">
<div className="border-bottom p-2 font-bold"></div>
<div className="p-2">
<Input
placeholder="搜索文件名称..."
value={filesSearch}
onChange={(e) => setFilesSearch(e.target.value)}
/>
</div>
<Table
scroll={{ y: 400 }}
rowKey="id"
size="small"
dataSource={files}
columns={fileCols.slice(1, fileCols.length)}
pagination={{
...filesPagination,
onChange: (page, pageSize) => {
const nextPageSize = pageSize || filesPagination.pageSize;
setFilesPagination((prev) => ({
...prev,
current: page,
pageSize: nextPageSize,
}));
fetchFiles({ page, pageSize: nextPageSize }).catch(() => {});
},
}}
onRow={(record: DatasetFile) => ({
onClick: () => toggleSelectFile(record),
})}
rowSelection={{
type: "checkbox",
selectedRowKeys: Object.keys(selectedFilesMap),
// 单选
onSelect: (record: DatasetFile) => {
toggleSelectFile(record);
},
// 全选
onSelectAll: (selected, selectedRows: DatasetFile[]) => {
if (selected) {
// ✔ 全选 -> 将 files 列表全部加入 selectedFilesMap
const newMap: Record<string, DatasetFile> = { ...selectedFilesMap };
selectedRows.forEach((f) => {
newMap[f.id] = f;
});
onSelectedFilesChange(newMap);
} else {
// ✘ 取消全选 -> 清空 map
const newMap = { ...selectedFilesMap };
Object.keys(newMap).forEach((id) => {
if (files.some((f) => String(f.id) === id)) {
// 仅移除当前页对应文件
delete newMap[id];
}
});
onSelectedFilesChange(newMap);
}
},
getCheckboxProps: (record: DatasetFile) => ({
name: record.fileName,
}),
}}
/>
</div>
</div>
<Button className="mt-4" onClick={() => setShowFiles(!showFiles)}>
{showFiles ? "取消预览" : "预览"}
</Button>
<div hidden={!showFiles}>
<Table
scroll={{ y: 400 }}
rowKey="id"
size="small"
dataSource={Object.values(selectedFilesMap)}
columns={fileCols}
/>
</div>
</div>
);
};
export default DatasetFileTransfer;
import React, { useCallback, useEffect } from "react";
import { Button, Input, Table } from "antd";
import { RightOutlined } from "@ant-design/icons";
import { mapDataset } from "@/pages/DataManagement/dataset.const";
import {
Dataset,
DatasetFile,
DatasetType,
} from "@/pages/DataManagement/dataset.model";
import {
queryDatasetFilesUsingGet,
queryDatasetsUsingGet,
} from "@/pages/DataManagement/dataset.api";
import { formatBytes } from "@/utils/unit";
import { useDebouncedEffect } from "@/hooks/useDebouncedEffect";
interface DatasetFileTransferProps
extends React.HTMLAttributes<HTMLDivElement> {
open: boolean;
selectedFilesMap: { [key: string]: DatasetFile };
onSelectedFilesChange: (filesMap: { [key: string]: DatasetFile }) => void;
onDatasetSelect?: (dataset: Dataset | null) => void;
}
const fileCols = [
{
title: "所属数据集",
dataIndex: "datasetName",
key: "datasetName",
ellipsis: true,
},
{
title: "文件名",
dataIndex: "fileName",
key: "fileName",
ellipsis: true,
},
{
title: "大小",
dataIndex: "fileSize",
key: "fileSize",
ellipsis: true,
render: formatBytes,
},
];
// Customize Table Transfer
const DatasetFileTransfer: React.FC<DatasetFileTransferProps> = ({
open,
selectedFilesMap,
onSelectedFilesChange,
onDatasetSelect,
...props
}) => {
const [datasets, setDatasets] = React.useState<Dataset[]>([]);
const [datasetSearch, setDatasetSearch] = React.useState<string>("");
const [datasetPagination, setDatasetPagination] = React.useState<{
current: number;
pageSize: number;
total: number;
}>({ current: 1, pageSize: 10, total: 0 });
const [files, setFiles] = React.useState<DatasetFile[]>([]);
const [filesSearch, setFilesSearch] = React.useState<string>("");
const [filesPagination, setFilesPagination] = React.useState<{
current: number;
pageSize: number;
total: number;
}>({ current: 1, pageSize: 10, total: 0 });
const [showFiles, setShowFiles] = React.useState<boolean>(false);
const [selectedDataset, setSelectedDataset] = React.useState<Dataset | null>(
null
);
const [datasetSelections, setDatasetSelections] = React.useState<Dataset[]>(
[]
);
const fetchDatasets = async () => {
const { data } = await queryDatasetsUsingGet({
// Ant Design Table pagination.current is 1-based; ensure backend also receives 1-based value
page: datasetPagination.current,
size: datasetPagination.pageSize,
keyword: datasetSearch,
type: DatasetType.TEXT,
});
setDatasets(data.content.map(mapDataset) || []);
setDatasetPagination((prev) => ({
...prev,
total: data.totalElements,
}));
};
useDebouncedEffect(
() => {
fetchDatasets();
},
[datasetSearch, datasetPagination.pageSize, datasetPagination.current],
300
);
const fetchFiles = useCallback(
async (
options?: Partial<{ page: number; pageSize: number; keyword: string }>
) => {
if (!selectedDataset) return;
const page = options?.page ?? filesPagination.current;
const pageSize = options?.pageSize ?? filesPagination.pageSize;
const keyword = options?.keyword ?? filesSearch;
const { data } = await queryDatasetFilesUsingGet(selectedDataset.id, {
page,
size: pageSize,
keyword,
});
setFiles(
(data.content || []).map((item: DatasetFile) => ({
...item,
key: item.id,
datasetName: selectedDataset.name,
}))
);
setFilesPagination((prev) => ({
...prev,
current: page,
pageSize,
total: data.totalElements,
}));
},
[selectedDataset, filesPagination.current, filesPagination.pageSize, filesSearch]
);
useEffect(() => {
// 当数据集变化时,重置文件分页并拉取第一页文件,避免额外的循环请求
if (selectedDataset) {
setFilesPagination({ current: 1, pageSize: 10, total: 0 });
fetchFiles({ page: 1, pageSize: 10 }).catch(() => {});
} else {
setFiles([]);
setFilesPagination({ current: 1, pageSize: 10, total: 0 });
}
// 只在 selectedDataset 变化时触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedDataset]);
useEffect(() => {
onDatasetSelect?.(selectedDataset);
}, [selectedDataset, onDatasetSelect]);
const toggleSelectFile = (record: DatasetFile) => {
if (!selectedFilesMap[record.id]) {
onSelectedFilesChange({
...selectedFilesMap,
[record.id]: record,
});
} else {
const newSelectedFiles = { ...selectedFilesMap };
delete newSelectedFiles[record.id];
onSelectedFilesChange(newSelectedFiles);
}
};
useEffect(() => {
if (!open) {
// 重置状态
setDatasets([]);
setDatasetSearch("");
setDatasetPagination({ current: 1, pageSize: 10, total: 0 });
setFiles([]);
setFilesSearch("");
setFilesPagination({ current: 1, pageSize: 10, total: 0 });
setShowFiles(false);
setSelectedDataset(null);
setDatasetSelections([]);
onDatasetSelect?.(null);
}
}, [open, onDatasetSelect]);
const datasetCols = [
{
title: "数据集名称",
dataIndex: "name",
key: "name",
ellipsis: true,
},
{
title: "文件数",
dataIndex: "fileCount",
key: "fileCount",
ellipsis: true,
},
{
title: "大小",
dataIndex: "totalSize",
key: "totalSize",
ellipsis: true,
render: formatBytes,
},
];
return (
<div {...props}>
<div className="grid grid-cols-25 gap-4 w-full">
<div className="border-card flex flex-col col-span-12">
<div className="border-bottom p-2 font-bold"></div>
<div className="p-2">
<Input
placeholder="搜索数据集名称..."
value={datasetSearch}
allowClear
onChange={(e) => setDatasetSearch(e.target.value)}
/>
</div>
<Table
scroll={{ y: 400 }}
rowKey="id"
size="small"
rowClassName={(record) =>
selectedDataset?.id === record.id ? "bg-blue-100" : ""
}
onRow={(record: Dataset) => ({
onClick: () => {
setSelectedDataset(record);
if (!datasetSelections.find((d) => d.id === record.id)) {
setDatasetSelections([...datasetSelections, record]);
} else {
setDatasetSelections(
datasetSelections.filter((d) => d.id !== record.id)
);
}
},
})}
dataSource={datasets}
columns={datasetCols}
pagination={{
...datasetPagination,
onChange: (page, pageSize) =>
setDatasetPagination({
current: page,
pageSize: pageSize || datasetPagination.pageSize,
total: datasetPagination.total,
}),
}}
/>
</div>
<RightOutlined />
<div className="border-card flex flex-col col-span-12">
<div className="border-bottom p-2 font-bold"></div>
<div className="p-2">
<Input
placeholder="搜索文件名称..."
value={filesSearch}
onChange={(e) => setFilesSearch(e.target.value)}
/>
</div>
<Table
scroll={{ y: 400 }}
rowKey="id"
size="small"
dataSource={files}
columns={fileCols.slice(1, fileCols.length)}
pagination={{
...filesPagination,
onChange: (page, pageSize) => {
const nextPageSize = pageSize || filesPagination.pageSize;
setFilesPagination((prev) => ({
...prev,
current: page,
pageSize: nextPageSize,
}));
fetchFiles({ page, pageSize: nextPageSize }).catch(() => {});
},
}}
onRow={(record: DatasetFile) => ({
onClick: () => toggleSelectFile(record),
})}
rowSelection={{
type: "checkbox",
selectedRowKeys: Object.keys(selectedFilesMap),
// 单选
onSelect: (record: DatasetFile) => {
toggleSelectFile(record);
},
// 全选
onSelectAll: (selected, selectedRows: DatasetFile[]) => {
if (selected) {
// ✔ 全选 -> 将 files 列表全部加入 selectedFilesMap
const newMap: Record<string, DatasetFile> = { ...selectedFilesMap };
selectedRows.forEach((f) => {
newMap[f.id] = f;
});
onSelectedFilesChange(newMap);
} else {
// ✘ 取消全选 -> 清空 map
const newMap = { ...selectedFilesMap };
Object.keys(newMap).forEach((id) => {
if (files.some((f) => String(f.id) === id)) {
// 仅移除当前页对应文件
delete newMap[id];
}
});
onSelectedFilesChange(newMap);
}
},
getCheckboxProps: (record: DatasetFile) => ({
name: record.fileName,
}),
}}
/>
</div>
</div>
<Button className="mt-4" onClick={() => setShowFiles(!showFiles)}>
{showFiles ? "取消预览" : "预览"}
</Button>
<div hidden={!showFiles}>
<Table
scroll={{ y: 400 }}
rowKey="id"
size="small"
dataSource={Object.values(selectedFilesMap)}
columns={fileCols}
/>
</div>
</div>
);
};
export default DatasetFileTransfer;

View File

@@ -1,251 +1,251 @@
import React, { useEffect, useState } from "react";
import { Drawer, Input, Button, App } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Edit, Save, TagIcon, X, Trash } from "lucide-react";
import { TagItem } from "@/pages/DataManagement/dataset.model";
interface CustomTagProps {
isEditable?: boolean;
tag: { id: number; name: string };
editingTag?: string | null;
editingTagValue?: string;
setEditingTag?: React.Dispatch<React.SetStateAction<string | null>>;
setEditingTagValue?: React.Dispatch<React.SetStateAction<string>>;
handleEditTag?: (tag: { id: number; name: string }, value: string) => void;
handleCancelEdit?: (tag: { id: number; name: string }) => void;
handleDeleteTag?: (tag: { id: number; name: string }) => void;
}
function CustomTag({
isEditable = false,
tag,
editingTag,
editingTagValue,
setEditingTag,
setEditingTagValue,
handleEditTag,
handleCancelEdit,
handleDeleteTag,
}: CustomTagProps) {
return (
<div
key={tag.id}
className="flex items-center justify-between px-4 py-2 border-card hover:bg-gray-50"
>
{editingTag?.id === tag.id ? (
<div className="flex gap-2 flex-1">
<Input
value={editingTagValue}
onChange={(e) => setEditingTagValue?.(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") {
handleEditTag?.(tag, editingTagValue);
}
if (e.key === "Escape") {
setEditingTag?.(null);
setEditingTagValue?.("");
}
}}
className="h-6 text-sm"
autoFocus
/>
<Button
onClick={() => handleEditTag(tag, editingTagValue)}
type="link"
size="small"
icon={<Save className="w-3 h-3" />}
/>
<Button
danger
type="text"
size="small"
onClick={() => handleCancelEdit?.(tag)}
icon={<X className="w-3 h-3" />}
/>
</div>
) : (
<>
<span className="text-sm">{tag.name}</span>
{isEditable && (
<div className="flex gap-1">
<Button
size="small"
type="text"
onClick={() => {
setEditingTag?.(tag);
setEditingTagValue?.(tag.name);
}}
icon={<Edit className="w-3 h-3" />}
/>
<Button
danger
type="text"
size="small"
onClick={() => handleDeleteTag?.(tag)}
icon={<Trash className="w-3 h-3" />}
/>
</div>
)}
</>
)}
</div>
);
}
const TagManager: React.FC = ({
onFetch,
onCreate,
onDelete,
onUpdate,
}: {
onFetch: () => Promise<any>;
onCreate: (tag: Pick<TagItem, "name">) => Promise<{ ok: boolean }>;
onDelete: (tagId: number) => Promise<{ ok: boolean }>;
onUpdate: (tag: TagItem) => Promise<{ ok: boolean }>;
}) => {
const [showTagManager, setShowTagManager] = useState(false);
const { message } = App.useApp();
const [tags, setTags] = useState<{ id: number; name: string }[]>([]);
const [newTag, setNewTag] = useState("");
const [editingTag, setEditingTag] = useState<string | null>(null);
const [editingTagValue, setEditingTagValue] = useState("");
// 获取标签列表
const fetchTags = async () => {
if (!onFetch) return;
try {
const { data } = await onFetch?.();
setTags(data || []);
} catch (e) {
message.error("获取标签失败");
}
};
// 添加标签
const addTag = async (tag: string) => {
try {
await onCreate?.({
name: tag,
});
fetchTags();
setNewTag("");
message.success("标签添加成功");
} catch (error) {
message.error("添加标签失败");
}
};
// 删除标签
const deleteTag = async (tag: TagItem) => {
try {
await onDelete?.(tag.id);
fetchTags();
message.success("标签删除成功");
} catch (error) {
message.error("删除标签失败");
}
};
const updateTag = async (oldTag: TagItem, newTag: string) => {
try {
await onUpdate?.({ ...oldTag, name: newTag });
fetchTags();
message.success("标签更新成功");
} catch (error) {
message.error("更新标签失败");
}
};
const handleCreateNewTag = () => {
if (newTag.trim()) {
addTag(newTag.trim());
setNewTag("");
}
};
const handleEditTag = (tag: TagItem, value: string) => {
if (value.trim()) {
updateTag(tag, value.trim());
setEditingTag(null);
setEditingTagValue("");
}
};
const handleCancelEdit = (tag: string) => {
setEditingTag(null);
setEditingTagValue("");
};
const handleDeleteTag = (tag: TagItem) => {
deleteTag(tag);
setEditingTag(null);
setEditingTagValue("");
};
useEffect(() => {
if (showTagManager) fetchTags();
}, [showTagManager]);
return (
<>
<Button
icon={<TagIcon className="w-4 h-4 mr-2" />}
onClick={() => setShowTagManager(true)}
>
</Button>
<Drawer
open={showTagManager}
onClose={() => setShowTagManager(false)}
title="标签管理"
width={500}
>
<div className="space-y-4 flex-overflow">
{/* Add New Tag */}
<div className="flex gap-2">
<Input
placeholder="输入标签名称..."
value={newTag}
allowClear
onChange={(e) => setNewTag(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") {
addTag(e.target.value);
}
}}
/>
<Button
type="primary"
onClick={handleCreateNewTag}
disabled={!newTag.trim()}
icon={<PlusOutlined />}
>
</Button>
</div>
<div className="flex-overflow">
<div className="overflow-auto grid grid-cols-2 gap-2">
{tags.map((tag) => (
<CustomTag
isEditable
key={tag.id}
tag={tag}
editingTag={editingTag}
editingTagValue={editingTagValue}
setEditingTag={setEditingTag}
setEditingTagValue={setEditingTagValue}
handleEditTag={handleEditTag}
handleCancelEdit={handleCancelEdit}
handleDeleteTag={handleDeleteTag}
/>
))}
</div>
</div>
</div>
</Drawer>
</>
);
};
export default TagManager;
import React, { useEffect, useState } from "react";
import { Drawer, Input, Button, App } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Edit, Save, TagIcon, X, Trash } from "lucide-react";
import { TagItem } from "@/pages/DataManagement/dataset.model";
interface CustomTagProps {
isEditable?: boolean;
tag: { id: number; name: string };
editingTag?: string | null;
editingTagValue?: string;
setEditingTag?: React.Dispatch<React.SetStateAction<string | null>>;
setEditingTagValue?: React.Dispatch<React.SetStateAction<string>>;
handleEditTag?: (tag: { id: number; name: string }, value: string) => void;
handleCancelEdit?: (tag: { id: number; name: string }) => void;
handleDeleteTag?: (tag: { id: number; name: string }) => void;
}
function CustomTag({
isEditable = false,
tag,
editingTag,
editingTagValue,
setEditingTag,
setEditingTagValue,
handleEditTag,
handleCancelEdit,
handleDeleteTag,
}: CustomTagProps) {
return (
<div
key={tag.id}
className="flex items-center justify-between px-4 py-2 border-card hover:bg-gray-50"
>
{editingTag?.id === tag.id ? (
<div className="flex gap-2 flex-1">
<Input
value={editingTagValue}
onChange={(e) => setEditingTagValue?.(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") {
handleEditTag?.(tag, editingTagValue);
}
if (e.key === "Escape") {
setEditingTag?.(null);
setEditingTagValue?.("");
}
}}
className="h-6 text-sm"
autoFocus
/>
<Button
onClick={() => handleEditTag(tag, editingTagValue)}
type="link"
size="small"
icon={<Save className="w-3 h-3" />}
/>
<Button
danger
type="text"
size="small"
onClick={() => handleCancelEdit?.(tag)}
icon={<X className="w-3 h-3" />}
/>
</div>
) : (
<>
<span className="text-sm">{tag.name}</span>
{isEditable && (
<div className="flex gap-1">
<Button
size="small"
type="text"
onClick={() => {
setEditingTag?.(tag);
setEditingTagValue?.(tag.name);
}}
icon={<Edit className="w-3 h-3" />}
/>
<Button
danger
type="text"
size="small"
onClick={() => handleDeleteTag?.(tag)}
icon={<Trash className="w-3 h-3" />}
/>
</div>
)}
</>
)}
</div>
);
}
const TagManager: React.FC = ({
onFetch,
onCreate,
onDelete,
onUpdate,
}: {
onFetch: () => Promise<any>;
onCreate: (tag: Pick<TagItem, "name">) => Promise<{ ok: boolean }>;
onDelete: (tagId: number) => Promise<{ ok: boolean }>;
onUpdate: (tag: TagItem) => Promise<{ ok: boolean }>;
}) => {
const [showTagManager, setShowTagManager] = useState(false);
const { message } = App.useApp();
const [tags, setTags] = useState<{ id: number; name: string }[]>([]);
const [newTag, setNewTag] = useState("");
const [editingTag, setEditingTag] = useState<string | null>(null);
const [editingTagValue, setEditingTagValue] = useState("");
// 获取标签列表
const fetchTags = async () => {
if (!onFetch) return;
try {
const { data } = await onFetch?.();
setTags(data || []);
} catch (e) {
message.error("获取标签失败");
}
};
// 添加标签
const addTag = async (tag: string) => {
try {
await onCreate?.({
name: tag,
});
fetchTags();
setNewTag("");
message.success("标签添加成功");
} catch (error) {
message.error("添加标签失败");
}
};
// 删除标签
const deleteTag = async (tag: TagItem) => {
try {
await onDelete?.(tag.id);
fetchTags();
message.success("标签删除成功");
} catch (error) {
message.error("删除标签失败");
}
};
const updateTag = async (oldTag: TagItem, newTag: string) => {
try {
await onUpdate?.({ ...oldTag, name: newTag });
fetchTags();
message.success("标签更新成功");
} catch (error) {
message.error("更新标签失败");
}
};
const handleCreateNewTag = () => {
if (newTag.trim()) {
addTag(newTag.trim());
setNewTag("");
}
};
const handleEditTag = (tag: TagItem, value: string) => {
if (value.trim()) {
updateTag(tag, value.trim());
setEditingTag(null);
setEditingTagValue("");
}
};
const handleCancelEdit = (tag: string) => {
setEditingTag(null);
setEditingTagValue("");
};
const handleDeleteTag = (tag: TagItem) => {
deleteTag(tag);
setEditingTag(null);
setEditingTagValue("");
};
useEffect(() => {
if (showTagManager) fetchTags();
}, [showTagManager]);
return (
<>
<Button
icon={<TagIcon className="w-4 h-4 mr-2" />}
onClick={() => setShowTagManager(true)}
>
</Button>
<Drawer
open={showTagManager}
onClose={() => setShowTagManager(false)}
title="标签管理"
width={500}
>
<div className="space-y-4 flex-overflow">
{/* Add New Tag */}
<div className="flex gap-2">
<Input
placeholder="输入标签名称..."
value={newTag}
allowClear
onChange={(e) => setNewTag(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") {
addTag(e.target.value);
}
}}
/>
<Button
type="primary"
onClick={handleCreateNewTag}
disabled={!newTag.trim()}
icon={<PlusOutlined />}
>
</Button>
</div>
<div className="flex-overflow">
<div className="overflow-auto grid grid-cols-2 gap-2">
{tags.map((tag) => (
<CustomTag
isEditable
key={tag.id}
tag={tag}
editingTag={editingTag}
editingTagValue={editingTagValue}
setEditingTag={setEditingTag}
setEditingTagValue={setEditingTagValue}
handleEditTag={handleEditTag}
handleCancelEdit={handleCancelEdit}
handleDeleteTag={handleDeleteTag}
/>
))}
</div>
</div>
</div>
</Drawer>
</>
);
};
export default TagManager;

View File

@@ -1,162 +1,162 @@
import { Button, Popover, Progress } from "antd";
import { Calendar, Clock, Play, Trash2, X } from "lucide-react";
interface TaskItem {
id: string;
name: string;
status: string;
progress: number;
scheduleConfig: {
type: string;
cronExpression?: string;
executionCount?: number;
maxExecutions?: number;
};
nextExecution?: string;
importConfig: {
source?: string;
};
createdAt: string;
}
export default function TaskPopover() {
const tasks: TaskItem[] = [
{
id: "1",
name: "导入客户数据",
status: "importing",
progress: 65,
scheduleConfig: {
type: "manual",
},
importConfig: {
source: "local",
},
createdAt: "2025-07-29 14:23",
},
{
id: "2",
name: "定时同步订单",
status: "waiting",
progress: 0,
scheduleConfig: {
type: "scheduled",
cronExpression: "0 0 * * *",
executionCount: 3,
maxExecutions: 10,
},
nextExecution: "2025-07-31 00:00",
importConfig: {
source: "api",
},
createdAt: "2025-07-28 09:10",
},
{
id: "3",
name: "清理历史日志",
status: "finished",
progress: 100,
scheduleConfig: {
type: "manual",
},
importConfig: {
source: "system",
},
createdAt: "2025-07-27 17:45",
},
];
return (
<Popover
placement="topLeft"
content={
<div className="w-[500px]">
<div className="flex items-center justify-between">
<h3 className="font-medium text-gray-900"></h3>
<Button type="text" className="h-6 w-6 p-0">
<X className="w-4 h-4 text-black-400 hover:text-gray-500" />
</Button>
</div>
<div className="p-2">
{tasks.length === 0 ? (
<div className="text-center py-8 text-gray-500">
<Clock className="w-8 h-8 mx-auto mb-2 text-gray-300" />
<p className="text-sm"></p>
</div>
) : (
<div className="space-y-2">
{tasks.map((task) => (
<div
key={task.id}
className="p-3 border-card hover:bg-gray-50"
>
<div className="space-y-2">
<div className="flex items-center justify-between">
<h4 className="font-medium text-sm truncate flex-1">
{task.name}
</h4>
<div className="flex items-center gap-2">
{task.status === "waiting" && (
<Button
className="h-6 w-6 p-0 text-blue-500 hover:text-blue-700"
title="立即执行"
>
<Play className="w-3 h-3" />
</Button>
)}
<Button className="h-6 w-6 p-0 text-gray-400 hover:text-red-500">
<Trash2 className="w-3 h-3" />
</Button>
</div>
</div>
{task.status === "importing" && (
<div className="space-y-1">
<div className="flex justify-between text-xs text-gray-500">
<span></span>
<span>{Math.round(task.progress)}%</span>
</div>
<Progress percent={task.progress} />
</div>
)}
{/* Schedule Information */}
{task.scheduleConfig.type === "scheduled" && (
<div className="text-xs text-gray-500 bg-gray-50 p-2 rounded">
<div className="flex items-center gap-1 mb-1">
<Calendar className="w-3 h-3" />
<span className="font-medium"></span>
</div>
<div>Cron: {task.scheduleConfig.cronExpression}</div>
{task.nextExecution && (
<div>: {task.nextExecution}</div>
)}
<div>
: {task.scheduleConfig.executionCount || 0}/
{task.scheduleConfig.maxExecutions || 10}
</div>
</div>
)}
<div className="flex items-center justify-between text-xs text-gray-400">
<span>
{task.importConfig.source === "local"
? "本地上传"
: task.importConfig.source || "未知来源"}
</span>
<span>{task.createdAt}</span>
</div>
</div>
</div>
))}
</div>
)}
</div>
</div>
}
>
<Button block></Button>
</Popover>
);
}
import { Button, Popover, Progress } from "antd";
import { Calendar, Clock, Play, Trash2, X } from "lucide-react";
interface TaskItem {
id: string;
name: string;
status: string;
progress: number;
scheduleConfig: {
type: string;
cronExpression?: string;
executionCount?: number;
maxExecutions?: number;
};
nextExecution?: string;
importConfig: {
source?: string;
};
createdAt: string;
}
export default function TaskPopover() {
const tasks: TaskItem[] = [
{
id: "1",
name: "导入客户数据",
status: "importing",
progress: 65,
scheduleConfig: {
type: "manual",
},
importConfig: {
source: "local",
},
createdAt: "2025-07-29 14:23",
},
{
id: "2",
name: "定时同步订单",
status: "waiting",
progress: 0,
scheduleConfig: {
type: "scheduled",
cronExpression: "0 0 * * *",
executionCount: 3,
maxExecutions: 10,
},
nextExecution: "2025-07-31 00:00",
importConfig: {
source: "api",
},
createdAt: "2025-07-28 09:10",
},
{
id: "3",
name: "清理历史日志",
status: "finished",
progress: 100,
scheduleConfig: {
type: "manual",
},
importConfig: {
source: "system",
},
createdAt: "2025-07-27 17:45",
},
];
return (
<Popover
placement="topLeft"
content={
<div className="w-[500px]">
<div className="flex items-center justify-between">
<h3 className="font-medium text-gray-900"></h3>
<Button type="text" className="h-6 w-6 p-0">
<X className="w-4 h-4 text-black-400 hover:text-gray-500" />
</Button>
</div>
<div className="p-2">
{tasks.length === 0 ? (
<div className="text-center py-8 text-gray-500">
<Clock className="w-8 h-8 mx-auto mb-2 text-gray-300" />
<p className="text-sm"></p>
</div>
) : (
<div className="space-y-2">
{tasks.map((task) => (
<div
key={task.id}
className="p-3 border-card hover:bg-gray-50"
>
<div className="space-y-2">
<div className="flex items-center justify-between">
<h4 className="font-medium text-sm truncate flex-1">
{task.name}
</h4>
<div className="flex items-center gap-2">
{task.status === "waiting" && (
<Button
className="h-6 w-6 p-0 text-blue-500 hover:text-blue-700"
title="立即执行"
>
<Play className="w-3 h-3" />
</Button>
)}
<Button className="h-6 w-6 p-0 text-gray-400 hover:text-red-500">
<Trash2 className="w-3 h-3" />
</Button>
</div>
</div>
{task.status === "importing" && (
<div className="space-y-1">
<div className="flex justify-between text-xs text-gray-500">
<span></span>
<span>{Math.round(task.progress)}%</span>
</div>
<Progress percent={task.progress} />
</div>
)}
{/* Schedule Information */}
{task.scheduleConfig.type === "scheduled" && (
<div className="text-xs text-gray-500 bg-gray-50 p-2 rounded">
<div className="flex items-center gap-1 mb-1">
<Calendar className="w-3 h-3" />
<span className="font-medium"></span>
</div>
<div>Cron: {task.scheduleConfig.cronExpression}</div>
{task.nextExecution && (
<div>: {task.nextExecution}</div>
)}
<div>
: {task.scheduleConfig.executionCount || 0}/
{task.scheduleConfig.maxExecutions || 10}
</div>
</div>
)}
<div className="flex items-center justify-between text-xs text-gray-400">
<span>
{task.importConfig.source === "local"
? "本地上传"
: task.importConfig.source || "未知来源"}
</span>
<span>{task.createdAt}</span>
</div>
</div>
</div>
))}
</div>
)}
</div>
</div>
}
>
<Button block></Button>
</Popover>
);
}

View File

@@ -1,17 +1,17 @@
import { useEffect } from "react";
export function useDebouncedEffect(
cb: () => void,
deps: any[] = [],
delay: number = 300
) {
useEffect(() => {
const handler = setTimeout(() => {
cb();
}, delay);
return () => {
clearTimeout(handler);
};
}, [...(deps || []), delay]);
}
import { useEffect } from "react";
export function useDebouncedEffect(
cb: () => void,
deps: any[] = [],
delay: number = 300
) {
useEffect(() => {
const handler = setTimeout(() => {
cb();
}, delay);
return () => {
clearTimeout(handler);
};
}, [...(deps || []), delay]);
}

View File

@@ -1,238 +1,236 @@
// 首页数据获取
// 支持轮询功能,使用示例:
// const { fetchData, startPolling, stopPolling, isPolling } = useFetchData(
// fetchFunction,
// mapFunction,
// 5000, // 5秒轮询一次,默认30秒
// true, // 是否自动开始轮询,默认 true
// [fetchStatistics, fetchOtherData] // 额外的轮询函数数组
// );
//
// startPolling(); // 开始轮询
// stopPolling(); // 停止轮询
// 手动调用 fetchData() 时,如果正在轮询,会重新开始轮询计时
// 轮询时会同时执行主要的 fetchFunction 和所有额外的轮询函数
import { useState, useRef, useEffect, useCallback } from "react";
import { useDebouncedEffect } from "./useDebouncedEffect";
import Loading from "@/utils/loading";
import { App } from "antd";
export default function useFetchData<T>(
fetchFunc: (params?: any) => Promise<any>,
mapDataFunc: (data: Partial<T>) => T = (data) => data as T,
pollingInterval: number = 30000, // 默认30秒轮询一次
autoRefresh: boolean = false, // 是否自动开始轮询,默认 false
additionalPollingFuncs: (() => Promise<any>)[] = [], // 额外的轮询函数
pageOffset: number = 1
) {
const { message } = App.useApp();
// 轮询相关状态
const [isPolling, setIsPolling] = useState(false);
const pollingTimerRef = useRef<NodeJS.Timeout | null>(null);
// 表格数据
const [tableData, setTableData] = useState<T[]>([]);
// 设置加载状态
const [loading, setLoading] = useState(false);
// 搜索参数
const [searchParams, setSearchParams] = useState({
keyword: "",
filter: {
type: [] as string[],
status: [] as string[],
tags: [] as string[],
// 通用分类筛选(如算子市场的分类 ID 列表)
categories: [] as string[],
},
current: 1,
pageSize: 12,
});
// 分页配置
const [pagination, setPagination] = useState({
total: 0,
showSizeChanger: true,
pageSizeOptions: ["12", "24", "48"],
showTotal: (total: number) => `${total}`,
onChange: (current: number, pageSize?: number) => {
setSearchParams((prev) => ({
...prev,
current,
pageSize: pageSize || prev.pageSize,
}));
},
});
const handleFiltersChange = (searchFilters: { [key: string]: string[] }) => {
setSearchParams({
...searchParams,
current: 1,
filter: { ...searchParams.filter, ...searchFilters },
});
};
const handleKeywordChange = (keyword: string) => {
setSearchParams({
...searchParams,
current: 1,
keyword: keyword,
});
};
function getFirstOfArray(arr: string[]) {
if (!arr || arr.length === 0 || !Array.isArray(arr)) return undefined;
if (arr[0] === "all") return undefined;
return arr[0];
}
// 清除轮询定时器
const clearPollingTimer = useCallback(() => {
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
pollingTimerRef.current = null;
}
}, []);
const fetchData = useCallback(
async (extraParams = {}, skipPollingRestart = false) => {
const { keyword, filter, current, pageSize } = searchParams;
if (!skipPollingRestart) {
Loading.show();
setLoading(true);
}
// 如果正在轮询且不是轮询触发的调用,先停止当前轮询
const wasPolling = isPolling && !skipPollingRestart;
if (wasPolling) {
clearPollingTimer();
}
try {
// 同时执行主要数据获取和额外的轮询函数
const promises = [
fetchFunc({
...Object.fromEntries(
Object.entries(filter).filter(([_, value]) => value != null && value.length > 0)
),
...extraParams,
keyword,
type: getFirstOfArray(filter?.type) || undefined,
status: getFirstOfArray(filter?.status) || undefined,
tags: filter?.tags?.length ? filter.tags.join(",") : undefined,
page: current - pageOffset,
size: pageSize, // Use camelCase for HTTP query params
}),
...additionalPollingFuncs.map((func) => func()),
];
const results = await Promise.all(promises);
const { data } = results[0]; // 主要数据结果
setPagination((prev) => ({
...prev,
total: data?.totalElements || 0,
}));
let result = [];
if (mapDataFunc) {
result = data?.content.map(mapDataFunc) ?? [];
}
setTableData(result);
// 如果之前正在轮询且不是轮询触发的调用,重新开始轮询
if (wasPolling) {
const poll = () => {
pollingTimerRef.current = setTimeout(() => {
fetchData({}, true).then(() => {
if (pollingTimerRef.current) {
poll();
}
});
}, pollingInterval);
};
poll();
}
} catch (error) {
console.error(error);
message.error("数据获取失败,请稍后重试");
} finally {
Loading.hide();
setLoading(false);
}
},
[
searchParams,
fetchFunc,
mapDataFunc,
isPolling,
clearPollingTimer,
pollingInterval,
message,
additionalPollingFuncs,
]
);
// 开始轮询
const startPolling = useCallback(() => {
clearPollingTimer();
setIsPolling(true);
const poll = () => {
pollingTimerRef.current = setTimeout(() => {
fetchData({}, true).then(() => {
if (pollingTimerRef.current) {
poll();
}
});
}, pollingInterval);
};
poll();
}, [pollingInterval, clearPollingTimer, fetchData]);
// 停止轮询
const stopPolling = useCallback(() => {
clearPollingTimer();
setIsPolling(false);
}, [clearPollingTimer]);
// 搜索参数变化时,自动刷新数据
// keyword 变化时,防抖500ms后刷新
useDebouncedEffect(
() => {
fetchData();
},
[searchParams],
searchParams?.keyword ? 500 : 0
);
// 组件卸载时清理轮询
useEffect(() => {
if (autoRefresh) {
startPolling();
}
return () => {
clearPollingTimer();
};
}, [clearPollingTimer]);
return {
loading,
tableData,
pagination: {
...pagination,
current: searchParams.current,
pageSize: searchParams.pageSize,
},
searchParams,
setSearchParams,
setPagination,
handleFiltersChange,
handleKeywordChange,
fetchData,
isPolling,
startPolling,
stopPolling,
};
}
// 首页数据获取
// 支持轮询功能,使用示例:
// const { fetchData, startPolling, stopPolling, isPolling } = useFetchData(
// fetchFunction,
// mapFunction,
// 5000, // 5秒轮询一次,默认30秒
// true, // 是否自动开始轮询,默认 true
// [fetchStatistics, fetchOtherData] // 额外的轮询函数数组
// );
//
// startPolling(); // 开始轮询
// stopPolling(); // 停止轮询
// 手动调用 fetchData() 时,如果正在轮询,会重新开始轮询计时
// 轮询时会同时执行主要的 fetchFunction 和所有额外的轮询函数
import { useState, useRef, useEffect, useCallback } from "react";
import { useDebouncedEffect } from "./useDebouncedEffect";
import Loading from "@/utils/loading";
import { App } from "antd";
export default function useFetchData<T>(
fetchFunc: (params?: any) => Promise<any>,
mapDataFunc: (data: Partial<T>) => T = (data) => data as T,
pollingInterval: number = 30000, // 默认30秒轮询一次
autoRefresh: boolean = false, // 是否自动开始轮询,默认 false
additionalPollingFuncs: (() => Promise<any>)[] = [], // 额外的轮询函数
pageOffset: number = 1
) {
const { message } = App.useApp();
// 轮询相关状态
const [isPolling, setIsPolling] = useState(false);
const pollingTimerRef = useRef<NodeJS.Timeout | null>(null);
// 表格数据
const [tableData, setTableData] = useState<T[]>([]);
// 设置加载状态
const [loading, setLoading] = useState(false);
// 搜索参数
const [searchParams, setSearchParams] = useState({
keyword: "",
filter: {
type: [] as string[],
status: [] as string[],
tags: [] as string[],
},
current: 1,
pageSize: 12,
});
// 分页配置
const [pagination, setPagination] = useState({
total: 0,
showSizeChanger: true,
pageSizeOptions: ["12", "24", "48"],
showTotal: (total: number) => `${total}`,
onChange: (current: number, pageSize?: number) => {
setSearchParams((prev) => ({
...prev,
current,
pageSize: pageSize || prev.pageSize,
}));
},
});
const handleFiltersChange = (searchFilters: { [key: string]: string[] }) => {
setSearchParams({
...searchParams,
current: 1,
filter: { ...searchParams.filter, ...searchFilters },
});
};
const handleKeywordChange = (keyword: string) => {
setSearchParams({
...searchParams,
current: 1,
keyword: keyword,
});
};
function getFirstOfArray(arr: string[]) {
if (!arr || arr.length === 0 || !Array.isArray(arr)) return undefined;
if (arr[0] === "all") return undefined;
return arr[0];
}
// 清除轮询定时器
const clearPollingTimer = useCallback(() => {
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
pollingTimerRef.current = null;
}
}, []);
const fetchData = useCallback(
async (extraParams = {}, skipPollingRestart = false) => {
const { keyword, filter, current, pageSize } = searchParams;
if (!skipPollingRestart) {
Loading.show();
setLoading(true);
}
// 如果正在轮询且不是轮询触发的调用,先停止当前轮询
const wasPolling = isPolling && !skipPollingRestart;
if (wasPolling) {
clearPollingTimer();
}
try {
// 同时执行主要数据获取和额外的轮询函数
const promises = [
fetchFunc({
...Object.fromEntries(
Object.entries(filter).filter(([_, value]) => value != null && value.length > 0)
),
...extraParams,
keyword,
type: getFirstOfArray(filter?.type) || undefined,
status: getFirstOfArray(filter?.status) || undefined,
tags: filter?.tags?.length ? filter.tags.join(",") : undefined,
page: current - pageOffset,
size: pageSize, // Use camelCase for HTTP query params
}),
...additionalPollingFuncs.map((func) => func()),
];
const results = await Promise.all(promises);
const { data } = results[0]; // 主要数据结果
setPagination((prev) => ({
...prev,
total: data?.totalElements || 0,
}));
let result = [];
if (mapDataFunc) {
result = data?.content.map(mapDataFunc) ?? [];
}
setTableData(result);
// 如果之前正在轮询且不是轮询触发的调用,重新开始轮询
if (wasPolling) {
const poll = () => {
pollingTimerRef.current = setTimeout(() => {
fetchData({}, true).then(() => {
if (pollingTimerRef.current) {
poll();
}
});
}, pollingInterval);
};
poll();
}
} catch (error) {
console.error(error);
message.error("数据获取失败,请稍后重试");
} finally {
Loading.hide();
setLoading(false);
}
},
[
searchParams,
fetchFunc,
mapDataFunc,
isPolling,
clearPollingTimer,
pollingInterval,
message,
additionalPollingFuncs,
]
);
// 开始轮询
const startPolling = useCallback(() => {
clearPollingTimer();
setIsPolling(true);
const poll = () => {
pollingTimerRef.current = setTimeout(() => {
fetchData({}, true).then(() => {
if (pollingTimerRef.current) {
poll();
}
});
}, pollingInterval);
};
poll();
}, [pollingInterval, clearPollingTimer, fetchData]);
// 停止轮询
const stopPolling = useCallback(() => {
clearPollingTimer();
setIsPolling(false);
}, [clearPollingTimer]);
// 搜索参数变化时,自动刷新数据
// keyword 变化时,防抖500ms后刷新
useDebouncedEffect(
() => {
fetchData();
},
[searchParams],
searchParams?.keyword ? 500 : 0
);
// 组件卸载时清理轮询
useEffect(() => {
if (autoRefresh) {
startPolling();
}
return () => {
clearPollingTimer();
};
}, [clearPollingTimer]);
return {
loading,
tableData,
pagination: {
...pagination,
current: searchParams.current,
pageSize: searchParams.pageSize,
},
searchParams,
setSearchParams,
setPagination,
handleFiltersChange,
handleKeywordChange,
fetchData,
isPolling,
startPolling,
stopPolling,
};
}

View File

@@ -1,52 +1,52 @@
import { useCallback, useEffect, useState } from "react";
import { useNavigate } from "react-router";
// 自定义hook:页面离开前提示
export function useLeavePrompt(shouldPrompt: boolean) {
const navigate = useNavigate();
const [showPrompt, setShowPrompt] = useState(false);
const [nextPath, setNextPath] = useState<string | null>(null);
// 浏览器刷新/关闭
useEffect(() => {
const handler = (e: BeforeUnloadEvent) => {
if (shouldPrompt) {
e.preventDefault();
e.returnValue = "";
return "";
}
};
window.addEventListener("beforeunload", handler);
return () => window.removeEventListener("beforeunload", handler);
}, [shouldPrompt]);
// 路由切换拦截
useEffect(() => {
const unblock = (window as any).__REACT_ROUTER_DOM_HISTORY__?.block?.(
(tx: any) => {
if (shouldPrompt) {
setShowPrompt(true);
setNextPath(tx.location.pathname);
return false;
}
return true;
}
);
return () => {
if (unblock) unblock();
};
}, [shouldPrompt]);
const confirmLeave = useCallback(() => {
setShowPrompt(false);
if (nextPath) {
navigate(nextPath, { replace: true });
}
}, [nextPath, navigate]);
return {
showPrompt,
setShowPrompt,
confirmLeave,
};
}
import { useCallback, useEffect, useState } from "react";
import { useNavigate } from "react-router";
// 自定义hook:页面离开前提示
export function useLeavePrompt(shouldPrompt: boolean) {
const navigate = useNavigate();
const [showPrompt, setShowPrompt] = useState(false);
const [nextPath, setNextPath] = useState<string | null>(null);
// 浏览器刷新/关闭
useEffect(() => {
const handler = (e: BeforeUnloadEvent) => {
if (shouldPrompt) {
e.preventDefault();
e.returnValue = "";
return "";
}
};
window.addEventListener("beforeunload", handler);
return () => window.removeEventListener("beforeunload", handler);
}, [shouldPrompt]);
// 路由切换拦截
useEffect(() => {
const unblock = (window as any).__REACT_ROUTER_DOM_HISTORY__?.block?.(
(tx: any) => {
if (shouldPrompt) {
setShowPrompt(true);
setNextPath(tx.location.pathname);
return false;
}
return true;
}
);
return () => {
if (unblock) unblock();
};
}, [shouldPrompt]);
const confirmLeave = useCallback(() => {
setShowPrompt(false);
if (nextPath) {
navigate(nextPath, { replace: true });
}
}, [nextPath, navigate]);
return {
showPrompt,
setShowPrompt,
confirmLeave,
};
}

View File

@@ -1,18 +1,18 @@
import { useMemo } from "react";
import { useLocation } from "react-router";
interface AnyObject {
[key: string]: any;
}
export function useSearchParams(): AnyObject {
const { search } = useLocation();
return useMemo(() => {
const urlParams = new URLSearchParams(search);
const params: AnyObject = {};
for (const [key, value] of urlParams.entries()) {
params[key] = value;
}
return params;
}, [search]);
}
import { useMemo } from "react";
import { useLocation } from "react-router";
interface AnyObject {
[key: string]: any;
}
export function useSearchParams(): AnyObject {
const { search } = useLocation();
return useMemo(() => {
const urlParams = new URLSearchParams(search);
const params: AnyObject = {};
for (const [key, value] of urlParams.entries()) {
params[key] = value;
}
return params;
}, [search]);
}

View File

@@ -1,187 +1,187 @@
import { TaskItem } from "@/pages/DataManagement/dataset.model";
import { calculateSHA256, checkIsFilesExist } from "@/utils/file.util";
import { App } from "antd";
import { useRef, useState } from "react";
export function useFileSliceUpload(
{
preUpload,
uploadChunk,
cancelUpload,
}: {
preUpload: (id: string, params: any) => Promise<{ data: number }>;
uploadChunk: (id: string, formData: FormData, config: any) => Promise<any>;
cancelUpload: ((reqId: number) => Promise<any>) | null;
},
showTaskCenter = true // 上传时是否显示任务中心
) {
const { message } = App.useApp();
const [taskList, setTaskList] = useState<TaskItem[]>([]);
const taskListRef = useRef<TaskItem[]>([]); // 用于固定任务顺序
const createTask = (detail: any = {}) => {
const { dataset } = detail;
const title = `上传数据集: ${dataset.name} `;
const controller = new AbortController();
const task: TaskItem = {
key: dataset.id,
title,
percent: 0,
reqId: -1,
controller,
size: 0,
updateEvent: detail.updateEvent,
hasArchive: detail.hasArchive,
};
taskListRef.current = [task, ...taskListRef.current];
setTaskList(taskListRef.current);
return task;
};
const updateTaskList = (task: TaskItem) => {
taskListRef.current = taskListRef.current.map((item) =>
item.key === task.key ? task : item
);
setTaskList(taskListRef.current);
};
const removeTask = (task: TaskItem) => {
const { key } = task;
taskListRef.current = taskListRef.current.filter(
(item) => item.key !== key
);
setTaskList(taskListRef.current);
if (task.isCancel && task.cancelFn) {
task.cancelFn();
}
if (task.updateEvent) window.dispatchEvent(new Event(task.updateEvent));
if (showTaskCenter) {
window.dispatchEvent(
new CustomEvent("show:task-popover", { detail: { show: false } })
);
}
};
async function buildFormData({ file, reqId, i, j }) {
const formData = new FormData();
const { slices, name, size } = file;
const checkSum = await calculateSHA256(slices[j]);
formData.append("file", slices[j]);
formData.append("reqId", reqId.toString());
formData.append("fileNo", (i + 1).toString());
formData.append("chunkNo", (j + 1).toString());
formData.append("fileName", name);
formData.append("fileSize", size.toString());
formData.append("totalChunkNum", slices.length.toString());
formData.append("checkSumHex", checkSum);
return formData;
}
async function uploadSlice(task: TaskItem, fileInfo) {
if (!task) {
return;
}
const { reqId, key } = task;
const { loaded, i, j, files, totalSize } = fileInfo;
const formData = await buildFormData({
file: files[i],
i,
j,
reqId,
});
let newTask = { ...task };
await uploadChunk(key, formData, {
onUploadProgress: (e) => {
const loadedSize = loaded + e.loaded;
const curPercent = Number((loadedSize / totalSize) * 100).toFixed(2);
newTask = {
...newTask,
...taskListRef.current.find((item) => item.key === key),
size: loadedSize,
percent: curPercent >= 100 ? 99.99 : curPercent,
};
updateTaskList(newTask);
},
});
}
async function uploadFile({ task, files, totalSize }) {
const { data: reqId } = await preUpload(task.key, {
totalFileNum: files.length,
totalSize,
datasetId: task.key,
hasArchive: task.hasArchive,
});
const newTask: TaskItem = {
...task,
reqId,
isCancel: false,
cancelFn: () => {
task.controller.abort();
cancelUpload?.(reqId);
if (task.updateEvent) window.dispatchEvent(new Event(task.updateEvent));
},
};
updateTaskList(newTask);
if (showTaskCenter) {
window.dispatchEvent(
new CustomEvent("show:task-popover", { detail: { show: true } })
);
}
// // 更新数据状态
if (task.updateEvent) window.dispatchEvent(new Event(task.updateEvent));
let loaded = 0;
for (let i = 0; i < files.length; i++) {
const { slices } = files[i];
for (let j = 0; j < slices.length; j++) {
await uploadSlice(newTask, {
loaded,
i,
j,
files,
totalSize,
});
loaded += slices[j].size;
}
}
removeTask(newTask);
}
const handleUpload = async ({ task, files }) => {
const isErrorFile = await checkIsFilesExist(files);
if (isErrorFile) {
message.error("文件被修改或删除,请重新选择文件上传");
removeTask({
...task,
isCancel: false,
...taskListRef.current.find((item) => item.key === task.key),
});
return;
}
try {
const totalSize = files.reduce((acc, file) => acc + file.size, 0);
await uploadFile({ task, files, totalSize });
} catch (err) {
console.error(err);
message.error("文件上传失败,请稍后重试");
removeTask({
...task,
isCancel: true,
...taskListRef.current.find((item) => item.key === task.key),
});
}
};
return {
taskList,
createTask,
removeTask,
handleUpload,
};
}
import { TaskItem } from "@/pages/DataManagement/dataset.model";
import { calculateSHA256, checkIsFilesExist } from "@/utils/file.util";
import { App } from "antd";
import { useRef, useState } from "react";
export function useFileSliceUpload(
{
preUpload,
uploadChunk,
cancelUpload,
}: {
preUpload: (id: string, params: any) => Promise<{ data: number }>;
uploadChunk: (id: string, formData: FormData, config: any) => Promise<any>;
cancelUpload: ((reqId: number) => Promise<any>) | null;
},
showTaskCenter = true // 上传时是否显示任务中心
) {
const { message } = App.useApp();
const [taskList, setTaskList] = useState<TaskItem[]>([]);
const taskListRef = useRef<TaskItem[]>([]); // 用于固定任务顺序
const createTask = (detail: any = {}) => {
const { dataset } = detail;
const title = `上传数据集: ${dataset.name} `;
const controller = new AbortController();
const task: TaskItem = {
key: dataset.id,
title,
percent: 0,
reqId: -1,
controller,
size: 0,
updateEvent: detail.updateEvent,
hasArchive: detail.hasArchive,
};
taskListRef.current = [task, ...taskListRef.current];
setTaskList(taskListRef.current);
return task;
};
const updateTaskList = (task: TaskItem) => {
taskListRef.current = taskListRef.current.map((item) =>
item.key === task.key ? task : item
);
setTaskList(taskListRef.current);
};
const removeTask = (task: TaskItem) => {
const { key } = task;
taskListRef.current = taskListRef.current.filter(
(item) => item.key !== key
);
setTaskList(taskListRef.current);
if (task.isCancel && task.cancelFn) {
task.cancelFn();
}
if (task.updateEvent) window.dispatchEvent(new Event(task.updateEvent));
if (showTaskCenter) {
window.dispatchEvent(
new CustomEvent("show:task-popover", { detail: { show: false } })
);
}
};
async function buildFormData({ file, reqId, i, j }) {
const formData = new FormData();
const { slices, name, size } = file;
const checkSum = await calculateSHA256(slices[j]);
formData.append("file", slices[j]);
formData.append("reqId", reqId.toString());
formData.append("fileNo", (i + 1).toString());
formData.append("chunkNo", (j + 1).toString());
formData.append("fileName", name);
formData.append("fileSize", size.toString());
formData.append("totalChunkNum", slices.length.toString());
formData.append("checkSumHex", checkSum);
return formData;
}
async function uploadSlice(task: TaskItem, fileInfo) {
if (!task) {
return;
}
const { reqId, key } = task;
const { loaded, i, j, files, totalSize } = fileInfo;
const formData = await buildFormData({
file: files[i],
i,
j,
reqId,
});
let newTask = { ...task };
await uploadChunk(key, formData, {
onUploadProgress: (e) => {
const loadedSize = loaded + e.loaded;
const curPercent = Number((loadedSize / totalSize) * 100).toFixed(2);
newTask = {
...newTask,
...taskListRef.current.find((item) => item.key === key),
size: loadedSize,
percent: curPercent >= 100 ? 99.99 : curPercent,
};
updateTaskList(newTask);
},
});
}
async function uploadFile({ task, files, totalSize }) {
const { data: reqId } = await preUpload(task.key, {
totalFileNum: files.length,
totalSize,
datasetId: task.key,
hasArchive: task.hasArchive,
});
const newTask: TaskItem = {
...task,
reqId,
isCancel: false,
cancelFn: () => {
task.controller.abort();
cancelUpload?.(reqId);
if (task.updateEvent) window.dispatchEvent(new Event(task.updateEvent));
},
};
updateTaskList(newTask);
if (showTaskCenter) {
window.dispatchEvent(
new CustomEvent("show:task-popover", { detail: { show: true } })
);
}
// // 更新数据状态
if (task.updateEvent) window.dispatchEvent(new Event(task.updateEvent));
let loaded = 0;
for (let i = 0; i < files.length; i++) {
const { slices } = files[i];
for (let j = 0; j < slices.length; j++) {
await uploadSlice(newTask, {
loaded,
i,
j,
files,
totalSize,
});
loaded += slices[j].size;
}
}
removeTask(newTask);
}
const handleUpload = async ({ task, files }) => {
const isErrorFile = await checkIsFilesExist(files);
if (isErrorFile) {
message.error("文件被修改或删除,请重新选择文件上传");
removeTask({
...task,
isCancel: false,
...taskListRef.current.find((item) => item.key === task.key),
});
return;
}
try {
const totalSize = files.reduce((acc, file) => acc + file.size, 0);
await uploadFile({ task, files, totalSize });
} catch (err) {
console.error(err);
message.error("文件上传失败,请稍后重试");
removeTask({
...task,
isCancel: true,
...taskListRef.current.find((item) => item.key === task.key),
});
}
};
return {
taskList,
createTask,
removeTask,
handleUpload,
};
}

View File

@@ -1,20 +1,20 @@
import { createStyles } from "antd-style";
const useStyle = createStyles(({ css, token }) => {
const { antCls } = token;
return {
customTable: css`
${antCls}-table {
${antCls}-table-container {
${antCls}-table-body, ${antCls}-table-content {
scrollbar-width: thin;
scrollbar-color: ${token.colorBorder} transparent;
scrollbar-gutter: stable;
}
}
}
`,
};
});
export default useStyle;
import { createStyles } from "antd-style";
const useStyle = createStyles(({ css, token }) => {
const { antCls } = token;
return {
customTable: css`
${antCls}-table {
${antCls}-table-container {
${antCls}-table-body, ${antCls}-table-content {
scrollbar-width: thin;
scrollbar-color: ${token.colorBorder} transparent;
scrollbar-gutter: stable;
}
}
}
`,
};
});
export default useStyle;

View File

@@ -1,67 +1,67 @@
import { useState, useEffect } from "react";
import { message } from "antd";
import { getTagConfigUsingGet } from "../pages/DataAnnotation/annotation.api";
import type { LabelStudioTagConfig } from "../pages/DataAnnotation/annotation.tagconfig";
import { parseTagConfig, type TagOption } from "../pages/DataAnnotation/annotation.tagconfig";
interface UseTagConfigReturn {
config: LabelStudioTagConfig | null;
objectOptions: TagOption[];
controlOptions: TagOption[];
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
}
/**
* Hook to fetch and manage Label Studio tag configuration
* @param includeLabelingOnly - If true, only include controls with category="labeling" (default: true)
*/
export function useTagConfig(includeLabelingOnly: boolean = true): UseTagConfigReturn {
const [config, setConfig] = useState<LabelStudioTagConfig | null>(null);
const [objectOptions, setObjectOptions] = useState<TagOption[]>([]);
const [controlOptions, setControlOptions] = useState<TagOption[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchConfig = async () => {
setLoading(true);
setError(null);
try {
const response = await getTagConfigUsingGet();
if (response.code === 200 && response.data) {
const tagConfig: LabelStudioTagConfig = response.data;
setConfig(tagConfig);
const { objectOptions: objects, controlOptions: controls } =
parseTagConfig(tagConfig, includeLabelingOnly);
setObjectOptions(objects);
setControlOptions(controls);
} else {
const errorMsg = response.message || "获取标签配置失败";
setError(errorMsg);
message.error(errorMsg);
}
} catch (err: any) {
const errorMsg = err.message || "加载标签配置时出错";
setError(errorMsg);
console.error("Failed to fetch tag config:", err);
message.error(errorMsg);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchConfig();
}, []);
return {
config,
objectOptions,
controlOptions,
loading,
error,
refetch: fetchConfig,
};
}
import { useState, useEffect } from "react";
import { message } from "antd";
import { getTagConfigUsingGet } from "../pages/DataAnnotation/annotation.api";
import type { LabelStudioTagConfig } from "../pages/DataAnnotation/annotation.tagconfig";
import { parseTagConfig, type TagOption } from "../pages/DataAnnotation/annotation.tagconfig";
interface UseTagConfigReturn {
config: LabelStudioTagConfig | null;
objectOptions: TagOption[];
controlOptions: TagOption[];
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
}
/**
* Hook to fetch and manage Label Studio tag configuration
* @param includeLabelingOnly - If true, only include controls with category="labeling" (default: true)
*/
export function useTagConfig(includeLabelingOnly: boolean = true): UseTagConfigReturn {
const [config, setConfig] = useState<LabelStudioTagConfig | null>(null);
const [objectOptions, setObjectOptions] = useState<TagOption[]>([]);
const [controlOptions, setControlOptions] = useState<TagOption[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchConfig = async () => {
setLoading(true);
setError(null);
try {
const response = await getTagConfigUsingGet();
if (response.code === 200 && response.data) {
const tagConfig: LabelStudioTagConfig = response.data;
setConfig(tagConfig);
const { objectOptions: objects, controlOptions: controls } =
parseTagConfig(tagConfig, includeLabelingOnly);
setObjectOptions(objects);
setControlOptions(controls);
} else {
const errorMsg = response.message || "获取标签配置失败";
setError(errorMsg);
message.error(errorMsg);
}
} catch (err: any) {
const errorMsg = err.message || "加载标签配置时出错";
setError(errorMsg);
console.error("Failed to fetch tag config:", err);
message.error(errorMsg);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchConfig();
}, []);
return {
config,
objectOptions,
controlOptions,
loading,
error,
refetch: fetchConfig,
};
}

View File

@@ -1,75 +1,75 @@
@import "tailwindcss";
/* components/TopLoadingBar.css */
.top-loading-bar {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 3px;
background-color: transparent;
z-index: 9999;
overflow: hidden;
}
.loading-bar-progress {
height: 100%;
background: linear-gradient(90deg, #3498db, #2ecc71, #3498db);
background-size: 200% 100%;
animation: gradient-animation 2s linear infinite, width-animation 0.3s ease;
transition: width 0.3s ease;
}
@keyframes gradient-animation {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
@keyframes width-animation {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.show-task-popover {
opacity: 100%;
visibility: visible;
transform: translateX(0);
}
@layer components {
.flex-center {
@apply flex items-center justify-center;
}
.flex-overflow-auto {
@apply flex-1 flex flex-col overflow-auto h-full;
}
.flex-overflow-hidden {
@apply flex flex-col h-full overflow-hidden;
}
.border-card {
@apply border border-[#f0f0f0] rounded-lg bg-white;
}
.border {
@apply border border-[#f0f0f0];
}
.border-bottom {
@apply border-b border-[#f0f0f0];
}
.border-top {
@apply border-t border-[#f0f0f0];
}
.border-right {
@apply border-r border-[#f0f0f0];
}
.border-left {
@apply border-l border-[#f0f0f0];
}
}
@import "tailwindcss";
/* components/TopLoadingBar.css */
.top-loading-bar {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 3px;
background-color: transparent;
z-index: 9999;
overflow: hidden;
}
.loading-bar-progress {
height: 100%;
background: linear-gradient(90deg, #3498db, #2ecc71, #3498db);
background-size: 200% 100%;
animation: gradient-animation 2s linear infinite, width-animation 0.3s ease;
transition: width 0.3s ease;
}
@keyframes gradient-animation {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
@keyframes width-animation {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.show-task-popover {
opacity: 100%;
visibility: visible;
transform: translateX(0);
}
@layer components {
.flex-center {
@apply flex items-center justify-center;
}
.flex-overflow-auto {
@apply flex-1 flex flex-col overflow-auto h-full;
}
.flex-overflow-hidden {
@apply flex flex-col h-full overflow-hidden;
}
.border-card {
@apply border border-[#f0f0f0] rounded-lg bg-white;
}
.border {
@apply border border-[#f0f0f0];
}
.border-bottom {
@apply border-b border-[#f0f0f0];
}
.border-top {
@apply border-t border-[#f0f0f0];
}
.border-right {
@apply border-r border-[#f0f0f0];
}
.border-left {
@apply border-l border-[#f0f0f0];
}
}

View File

@@ -1,22 +1,22 @@
import { StrictMode, Suspense } from "react";
import { createRoot } from "react-dom/client";
import { RouterProvider } from "react-router";
import router from "./routes/routes";
import { App as AntdApp, Spin } from "antd";
import "./index.css";
import TopLoadingBar from "./components/TopLoadingBar";
import { store } from "./store";
import { Provider } from "react-redux";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Provider store={store}>
<AntdApp>
<Suspense fallback={<Spin />}>
<TopLoadingBar />
<RouterProvider router={router} />
</Suspense>
</AntdApp>
</Provider>
</StrictMode>
);
import { StrictMode, Suspense } from "react";
import { createRoot } from "react-dom/client";
import { RouterProvider } from "react-router";
import router from "./routes/routes";
import { App as AntdApp, Spin } from "antd";
import "./index.css";
import TopLoadingBar from "./components/TopLoadingBar";
import { store } from "./store";
import { Provider } from "react-redux";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Provider store={store}>
<AntdApp>
<Suspense fallback={<Spin />}>
<TopLoadingBar />
<RouterProvider router={router} />
</Suspense>
</AntdApp>
</Provider>
</StrictMode>
);

View File

@@ -1,330 +1,330 @@
import { BarChart, Circle, Grid, ImageIcon, Layers, Maximize, MousePointer, Move, Square, Target, Crop, RotateCcw, FileText, Tag, Heart, HelpCircle, BookOpen, MessageSquare, Users, Zap, Globe, Scissors } from "lucide-react";
// Define the AnnotationTask type if not imported from elsewhere
interface AnnotationTask {
id: string
name: string
completed: string
completedCount: number
skippedCount: number
totalCount: number
annotators: Array<{
id: string
name: string
avatar?: string
}>
text: string
status: "completed" | "in_progress" | "pending" | "skipped"
project: string
type: "图像分类" | "文本分类" | "目标检测" | "NER" | "语音识别" | "视频分析"
datasetType: "text" | "image" | "video" | "audio"
progress: number
}
export const mockTasks: AnnotationTask[] = [
{
id: "12345678",
name: "图像分类标注任务",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [
{ id: "1", name: "张三", avatar: "/placeholder-user.jpg" },
{ id: "2", name: "李四", avatar: "/placeholder-user.jpg" },
],
text: "对产品图像进行分类标注,包含10个类别",
status: "completed",
project: "图像分类",
type: "图像分类",
datasetType: "image",
progress: 100,
},
{
id: "12345679",
name: "文本情感分析标注",
completed: "2024年1月20日 20:40",
completedCount: 2,
skippedCount: 0,
totalCount: 2,
annotators: [
{ id: "1", name: "王五", avatar: "/placeholder-user.jpg" },
{ id: "2", name: "赵六", avatar: "/placeholder-user.jpg" },
],
text: "对用户评论进行情感倾向标注",
status: "completed",
project: "文本分类",
type: "文本分类",
datasetType: "text",
progress: 100,
},
{
id: "12345680",
name: "目标检测标注任务",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [{ id: "1", name: "孙七", avatar: "/placeholder-user.jpg" }],
text: "对交通场景图像进行目标检测标注",
status: "in_progress",
project: "目标检测",
type: "目标检测",
datasetType: "image",
progress: 50,
},
{
id: "12345681",
name: "命名实体识别标注",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [{ id: "1", name: "周八", avatar: "/placeholder-user.jpg" }],
text: "对新闻文本进行命名实体识别标注",
status: "in_progress",
project: "NER",
type: "NER",
datasetType: "text",
progress: 75,
},
{
id: "12345682",
name: "语音识别标注任务",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [{ id: "1", name: "吴九", avatar: "/placeholder-user.jpg" }],
text: "对语音数据进行转录和标注",
status: "in_progress",
project: "语音识别",
type: "语音识别",
datasetType: "audio",
progress: 25,
},
{
id: "12345683",
name: "视频动作识别标注",
completed: "2024年1月20日 20:40",
completedCount: 0,
skippedCount: 2,
totalCount: 2,
annotators: [
{ id: "1", name: "陈十", avatar: "/placeholder-user.jpg" },
{ id: "2", name: "林十一", avatar: "/placeholder-user.jpg" },
],
text: "对视频中的人体动作进行识别和标注",
status: "skipped",
project: "视频分析",
type: "视频分析",
datasetType: "video",
progress: 0,
},
]
// Define the Template type
type Template = {
id: string;
name: string;
category: string;
description: string;
type: string;
preview?: string;
icon: React.ReactNode;
};
// 扩展的预制模板数据
export const mockTemplates: Template[] = [
// 计算机视觉模板
{
id: "cv-1",
name: "目标检测",
category: "Computer Vision",
description: "使用边界框标注图像中的目标对象",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Object+Detection",
icon: <Square className="w-4 h-4" />,
},
{
id: "cv-2",
name: "语义分割(多边形)",
category: "Computer Vision",
description: "使用多边形精确标注图像中的区域",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Polygon+Segmentation",
icon: <Layers className="w-4 h-4" />,
},
{
id: "cv-3",
name: "语义分割(掩码)",
category: "Computer Vision",
description: "使用像素级掩码标注图像区域",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Mask+Segmentation",
icon: <Circle className="w-4 h-4" />,
},
{
id: "cv-4",
name: "关键点标注",
category: "Computer Vision",
description: "标注图像中的关键点位置",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Keypoint+Labeling",
icon: <MousePointer className="w-4 h-4" />,
},
{
id: "cv-5",
name: "图像分类",
category: "Computer Vision",
description: "为整个图像分配类别标签",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Classification",
icon: <ImageIcon className="w-4 h-4" />,
},
{
id: "cv-6",
name: "实例分割",
category: "Computer Vision",
description: "区分同类别的不同实例对象",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Instance+Segmentation",
icon: <Target className="w-4 h-4" />,
},
{
id: "cv-7",
name: "全景分割",
category: "Computer Vision",
description: "结合语义分割和实例分割的全景标注",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Panoptic+Segmentation",
icon: <Grid className="w-4 h-4" />,
},
{
id: "cv-8",
name: "3D目标检测",
category: "Computer Vision",
description: "在3D空间中标注目标对象的位置和方向",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=3D+Object+Detection",
icon: <Maximize className="w-4 h-4" />,
},
{
id: "cv-9",
name: "图像配对",
category: "Computer Vision",
description: "标注图像之间的对应关系",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Matching",
icon: <Move className="w-4 h-4" />,
},
{
id: "cv-10",
name: "图像质量评估",
category: "Computer Vision",
description: "评估和标注图像质量等级",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Quality+Assessment",
icon: <BarChart className="w-4 h-4" />,
},
{
id: "cv-11",
name: "图像裁剪标注",
category: "Computer Vision",
description: "标注图像中需要裁剪的区域",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Cropping",
icon: <Crop className="w-4 h-4" />,
},
{
id: "cv-12",
name: "图像旋转标注",
category: "Computer Vision",
description: "标注图像的正确方向角度",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Rotation",
icon: <RotateCcw className="w-4 h-4" />,
},
// 自然语言处理模板
{
id: "nlp-1",
name: "文本分类",
category: "Natural Language Processing",
description: "为文本分配类别标签",
type: "text",
icon: <FileText className="w-4 h-4" />,
},
{
id: "nlp-2",
name: "命名实体识别",
category: "Natural Language Processing",
description: "识别和标注文本中的实体",
type: "text",
icon: <Tag className="w-4 h-4" />,
},
{
id: "nlp-3",
name: "情感分析",
category: "Natural Language Processing",
description: "标注文本的情感倾向",
type: "text",
icon: <Heart className="w-4 h-4" />,
},
{
id: "nlp-4",
name: "问答标注",
category: "Natural Language Processing",
description: "标注问题和答案对",
type: "text",
icon: <HelpCircle className="w-4 h-4" />,
},
{
id: "nlp-5",
name: "文本摘要",
category: "Natural Language Processing",
description: "为长文本创建摘要标注",
type: "text",
icon: <BookOpen className="w-4 h-4" />,
},
{
id: "nlp-6",
name: "对话标注",
category: "Natural Language Processing",
description: "标注对话中的意图和实体",
type: "text",
icon: <MessageSquare className="w-4 h-4" />,
},
{
id: "nlp-7",
name: "关系抽取",
category: "Natural Language Processing",
description: "标注实体之间的关系",
type: "text",
icon: <Users className="w-4 h-4" />,
},
{
id: "nlp-8",
name: "文本相似度",
category: "Natural Language Processing",
description: "标注文本之间的相似度",
type: "text",
icon: <Zap className="w-4 h-4" />,
},
{
id: "nlp-9",
name: "语言检测",
category: "Natural Language Processing",
description: "识别和标注文本的语言类型",
type: "text",
icon: <Globe className="w-4 h-4" />,
},
{
id: "nlp-10",
name: "文本纠错",
category: "Natural Language Processing",
description: "标注文本中的错误并提供修正",
type: "text",
icon: <Scissors className="w-4 h-4" />,
},
import { BarChart, Circle, Grid, ImageIcon, Layers, Maximize, MousePointer, Move, Square, Target, Crop, RotateCcw, FileText, Tag, Heart, HelpCircle, BookOpen, MessageSquare, Users, Zap, Globe, Scissors } from "lucide-react";
// Define the AnnotationTask type if not imported from elsewhere
interface AnnotationTask {
id: string
name: string
completed: string
completedCount: number
skippedCount: number
totalCount: number
annotators: Array<{
id: string
name: string
avatar?: string
}>
text: string
status: "completed" | "in_progress" | "pending" | "skipped"
project: string
type: "图像分类" | "文本分类" | "目标检测" | "NER" | "语音识别" | "视频分析"
datasetType: "text" | "image" | "video" | "audio"
progress: number
}
export const mockTasks: AnnotationTask[] = [
{
id: "12345678",
name: "图像分类标注任务",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [
{ id: "1", name: "张三", avatar: "/placeholder-user.jpg" },
{ id: "2", name: "李四", avatar: "/placeholder-user.jpg" },
],
text: "对产品图像进行分类标注,包含10个类别",
status: "completed",
project: "图像分类",
type: "图像分类",
datasetType: "image",
progress: 100,
},
{
id: "12345679",
name: "文本情感分析标注",
completed: "2024年1月20日 20:40",
completedCount: 2,
skippedCount: 0,
totalCount: 2,
annotators: [
{ id: "1", name: "王五", avatar: "/placeholder-user.jpg" },
{ id: "2", name: "赵六", avatar: "/placeholder-user.jpg" },
],
text: "对用户评论进行情感倾向标注",
status: "completed",
project: "文本分类",
type: "文本分类",
datasetType: "text",
progress: 100,
},
{
id: "12345680",
name: "目标检测标注任务",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [{ id: "1", name: "孙七", avatar: "/placeholder-user.jpg" }],
text: "对交通场景图像进行目标检测标注",
status: "in_progress",
project: "目标检测",
type: "目标检测",
datasetType: "image",
progress: 50,
},
{
id: "12345681",
name: "命名实体识别标注",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [{ id: "1", name: "周八", avatar: "/placeholder-user.jpg" }],
text: "对新闻文本进行命名实体识别标注",
status: "in_progress",
project: "NER",
type: "NER",
datasetType: "text",
progress: 75,
},
{
id: "12345682",
name: "语音识别标注任务",
completed: "2024年1月20日 20:40",
completedCount: 1,
skippedCount: 0,
totalCount: 2,
annotators: [{ id: "1", name: "吴九", avatar: "/placeholder-user.jpg" }],
text: "对语音数据进行转录和标注",
status: "in_progress",
project: "语音识别",
type: "语音识别",
datasetType: "audio",
progress: 25,
},
{
id: "12345683",
name: "视频动作识别标注",
completed: "2024年1月20日 20:40",
completedCount: 0,
skippedCount: 2,
totalCount: 2,
annotators: [
{ id: "1", name: "陈十", avatar: "/placeholder-user.jpg" },
{ id: "2", name: "林十一", avatar: "/placeholder-user.jpg" },
],
text: "对视频中的人体动作进行识别和标注",
status: "skipped",
project: "视频分析",
type: "视频分析",
datasetType: "video",
progress: 0,
},
]
// Define the Template type
type Template = {
id: string;
name: string;
category: string;
description: string;
type: string;
preview?: string;
icon: React.ReactNode;
};
// 扩展的预制模板数据
export const mockTemplates: Template[] = [
// 计算机视觉模板
{
id: "cv-1",
name: "目标检测",
category: "Computer Vision",
description: "使用边界框标注图像中的目标对象",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Object+Detection",
icon: <Square className="w-4 h-4" />,
},
{
id: "cv-2",
name: "语义分割(多边形)",
category: "Computer Vision",
description: "使用多边形精确标注图像中的区域",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Polygon+Segmentation",
icon: <Layers className="w-4 h-4" />,
},
{
id: "cv-3",
name: "语义分割(掩码)",
category: "Computer Vision",
description: "使用像素级掩码标注图像区域",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Mask+Segmentation",
icon: <Circle className="w-4 h-4" />,
},
{
id: "cv-4",
name: "关键点标注",
category: "Computer Vision",
description: "标注图像中的关键点位置",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Keypoint+Labeling",
icon: <MousePointer className="w-4 h-4" />,
},
{
id: "cv-5",
name: "图像分类",
category: "Computer Vision",
description: "为整个图像分配类别标签",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Classification",
icon: <ImageIcon className="w-4 h-4" />,
},
{
id: "cv-6",
name: "实例分割",
category: "Computer Vision",
description: "区分同类别的不同实例对象",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Instance+Segmentation",
icon: <Target className="w-4 h-4" />,
},
{
id: "cv-7",
name: "全景分割",
category: "Computer Vision",
description: "结合语义分割和实例分割的全景标注",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Panoptic+Segmentation",
icon: <Grid className="w-4 h-4" />,
},
{
id: "cv-8",
name: "3D目标检测",
category: "Computer Vision",
description: "在3D空间中标注目标对象的位置和方向",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=3D+Object+Detection",
icon: <Maximize className="w-4 h-4" />,
},
{
id: "cv-9",
name: "图像配对",
category: "Computer Vision",
description: "标注图像之间的对应关系",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Matching",
icon: <Move className="w-4 h-4" />,
},
{
id: "cv-10",
name: "图像质量评估",
category: "Computer Vision",
description: "评估和标注图像质量等级",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Quality+Assessment",
icon: <BarChart className="w-4 h-4" />,
},
{
id: "cv-11",
name: "图像裁剪标注",
category: "Computer Vision",
description: "标注图像中需要裁剪的区域",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Cropping",
icon: <Crop className="w-4 h-4" />,
},
{
id: "cv-12",
name: "图像旋转标注",
category: "Computer Vision",
description: "标注图像的正确方向角度",
type: "image",
preview: "/placeholder.svg?height=120&width=180&text=Image+Rotation",
icon: <RotateCcw className="w-4 h-4" />,
},
// 自然语言处理模板
{
id: "nlp-1",
name: "文本分类",
category: "Natural Language Processing",
description: "为文本分配类别标签",
type: "text",
icon: <FileText className="w-4 h-4" />,
},
{
id: "nlp-2",
name: "命名实体识别",
category: "Natural Language Processing",
description: "识别和标注文本中的实体",
type: "text",
icon: <Tag className="w-4 h-4" />,
},
{
id: "nlp-3",
name: "情感分析",
category: "Natural Language Processing",
description: "标注文本的情感倾向",
type: "text",
icon: <Heart className="w-4 h-4" />,
},
{
id: "nlp-4",
name: "问答标注",
category: "Natural Language Processing",
description: "标注问题和答案对",
type: "text",
icon: <HelpCircle className="w-4 h-4" />,
},
{
id: "nlp-5",
name: "文本摘要",
category: "Natural Language Processing",
description: "为长文本创建摘要标注",
type: "text",
icon: <BookOpen className="w-4 h-4" />,
},
{
id: "nlp-6",
name: "对话标注",
category: "Natural Language Processing",
description: "标注对话中的意图和实体",
type: "text",
icon: <MessageSquare className="w-4 h-4" />,
},
{
id: "nlp-7",
name: "关系抽取",
category: "Natural Language Processing",
description: "标注实体之间的关系",
type: "text",
icon: <Users className="w-4 h-4" />,
},
{
id: "nlp-8",
name: "文本相似度",
category: "Natural Language Processing",
description: "标注文本之间的相似度",
type: "text",
icon: <Zap className="w-4 h-4" />,
},
{
id: "nlp-9",
name: "语言检测",
category: "Natural Language Processing",
description: "识别和标注文本的语言类型",
type: "text",
icon: <Globe className="w-4 h-4" />,
},
{
id: "nlp-10",
name: "文本纠错",
category: "Natural Language Processing",
description: "标注文本中的错误并提供修正",
type: "text",
icon: <Scissors className="w-4 h-4" />,
},
]

View File

@@ -1,290 +1,290 @@
// 预设评估维度配置
export const presetEvaluationDimensions: EvaluationDimension[] = [
{
id: "answer_relevance",
name: "回答相关性",
description: "评估回答内容是否针对问题,是否切中要点",
category: "accuracy",
isEnabled: true,
},
{
id: "content_quality",
name: "内容质量",
description: "评估内容的准确性、完整性和可读性",
category: "quality",
isEnabled: true,
},
{
id: "information_completeness",
name: "信息完整性",
description: "评估信息是否完整,无缺失关键内容",
category: "completeness",
isEnabled: true,
},
{
id: "language_fluency",
name: "语言流畅性",
description: "评估语言表达是否流畅自然",
category: "quality",
isEnabled: true,
},
{
id: "factual_accuracy",
name: "事实准确性",
description: "评估内容中事实信息的准确性",
category: "accuracy",
isEnabled: true,
},
]
export const sliceOperators: SliceOperator[] = [
{
id: "paragraph-split",
name: "段落分割",
description: "按段落自然分割文档",
type: "text",
icon: "📄",
params: { minLength: 50, maxLength: 1000 },
},
{
id: "sentence-split",
name: "句子分割",
description: "按句子边界分割文档",
type: "text",
icon: "📝",
params: { maxSentences: 5, overlap: 1 },
},
{
id: "semantic-split",
name: "语义分割",
description: "基于语义相似度智能分割",
type: "semantic",
icon: "🧠",
params: { threshold: 0.7, windowSize: 3 },
},
{
id: "length-split",
name: "长度分割",
description: "按固定字符长度分割",
type: "text",
icon: "📏",
params: { chunkSize: 512, overlap: 50 },
},
{
id: "structure-split",
name: "结构化分割",
description: "按文档结构(标题、章节)分割",
type: "structure",
icon: "🏗️",
params: { preserveHeaders: true, minSectionLength: 100 },
},
{
id: "table-extract",
name: "表格提取",
description: "提取并单独处理表格内容",
type: "structure",
icon: "📊",
params: { includeHeaders: true, mergeRows: false },
},
{
id: "code-extract",
name: "代码提取",
description: "识别并提取代码块",
type: "custom",
icon: "💻",
params: { languages: ["python", "javascript", "sql"], preserveIndentation: true },
},
{
id: "qa-extract",
name: "问答提取",
description: "自动识别问答格式内容",
type: "semantic",
icon: "❓",
params: { confidenceThreshold: 0.8, generateAnswers: true },
},
]
export const mockTasks: EvaluationTask[] = [
{
id: "1",
name: "客服对话数据质量评估",
datasetId: "1",
datasetName: "客服对话数据集",
evaluationType: "model",
status: "completed",
score: 85,
progress: 100,
createdAt: "2024-01-15 14:30",
completedAt: "2024-01-15 14:45",
description: "评估客服对话数据的质量,包括对话完整性、回复准确性等维度",
dimensions: ["answer_relevance", "content_quality", "information_completeness"],
customDimensions: [],
sliceConfig: {
threshold: 0.8,
sampleCount: 100,
method: "语义分割",
},
modelConfig: {
url: "https://api.openai.com/v1/chat/completions",
apiKey: "sk-***",
prompt: "请从数据质量、标签准确性、标注一致性三个维度评估这个客服对话数据集...",
temperature: 0.3,
maxTokens: 2000,
},
metrics: {
accuracy: 88,
completeness: 92,
consistency: 78,
relevance: 85,
},
issues: [
{ type: "重复数据", count: 23, severity: "medium" },
{ type: "格式错误", count: 5, severity: "high" },
{ type: "内容不完整", count: 12, severity: "low" },
],
},
{
id: "2",
name: "产品评论人工评估",
datasetId: "2",
datasetName: "产品评论数据集",
evaluationType: "manual",
status: "pending",
progress: 0,
createdAt: "2024-01-15 15:20",
description: "人工评估产品评论数据的情感标注准确性",
dimensions: ["content_quality", "factual_accuracy"],
customDimensions: [
{
id: "custom_1",
name: "情感极性准确性",
description: "评估情感标注的极性(正面/负面/中性)准确性",
category: "custom",
isCustom: true,
isEnabled: true,
},
],
sliceConfig: {
threshold: 0.7,
sampleCount: 50,
method: "段落分割",
},
metrics: {
accuracy: 0,
completeness: 0,
consistency: 0,
relevance: 0,
},
issues: [],
},
{
id: "3",
name: "新闻分类数据评估",
datasetId: "4",
datasetName: "新闻分类数据集",
evaluationType: "manual",
status: "running",
progress: 65,
createdAt: "2024-01-15 16:10",
description: "人工评估新闻分类数据集的标注质量",
dimensions: ["content_quality", "information_completeness", "factual_accuracy"],
customDimensions: [],
sliceConfig: {
threshold: 0.9,
sampleCount: 80,
method: "句子分割",
},
metrics: {
accuracy: 82,
completeness: 78,
consistency: 85,
relevance: 80,
},
issues: [{ type: "标注不一致", count: 15, severity: "medium" }],
},
]
// 模拟QA对数据
export const mockQAPairs: QAPair[] = [
{
id: "qa_1",
question: "这个产品的退货政策是什么?",
answer: "我们提供7天无理由退货服务,商品需要保持原包装完整。",
sliceId: "slice_1",
score: 4.5,
feedback: "回答准确且完整",
},
{
id: "qa_2",
question: "如何联系客服?",
answer: "您可以通过在线客服、电话400-123-4567或邮箱service@company.com联系我们。",
sliceId: "slice_2",
score: 5.0,
feedback: "提供了多种联系方式,非常全面",
},
{
id: "qa_3",
question: "配送时间需要多久?",
answer: "一般情况下,我们会在1-3个工作日内发货,配送时间根据地区不同为2-7天。",
sliceId: "slice_3",
score: 4.0,
feedback: "时间范围说明清楚",
},
]
// 评估维度模板配置
export const evaluationTemplates = {
dialogue_text: {
name: "对话文本评估",
dimensions: [
{
id: "answer_relevance",
name: "回答是否有针对性",
description: "评估回答内容是否针对问题,是否切中要点",
category: "accuracy" as const,
isEnabled: true,
},
{
id: "question_correctness",
name: "问题是否正确",
description: "评估问题表述是否清晰、准确、合理",
category: "quality" as const,
isEnabled: true,
},
{
id: "answer_independence",
name: "回答是否独立",
description: "评估回答是否独立完整,不依赖外部信息",
category: "completeness" as const,
isEnabled: true,
},
],
},
data_quality: {
name: "数据质量评估",
dimensions: [
{
id: "data_quality",
name: "数据质量",
description: "评估数据的整体质量,包括格式规范性、完整性等",
category: "quality" as const,
isEnabled: true,
},
{
id: "label_accuracy",
name: "标签准确性",
description: "评估数据标签的准确性和一致性",
category: "accuracy" as const,
isEnabled: true,
},
{
id: "data_completeness",
name: "数据完整性",
description: "评估数据集的完整性,是否存在缺失数据",
category: "completeness" as const,
isEnabled: true,
},
],
},
// 预设评估维度配置
export const presetEvaluationDimensions: EvaluationDimension[] = [
{
id: "answer_relevance",
name: "回答相关性",
description: "评估回答内容是否针对问题,是否切中要点",
category: "accuracy",
isEnabled: true,
},
{
id: "content_quality",
name: "内容质量",
description: "评估内容的准确性、完整性和可读性",
category: "quality",
isEnabled: true,
},
{
id: "information_completeness",
name: "信息完整性",
description: "评估信息是否完整,无缺失关键内容",
category: "completeness",
isEnabled: true,
},
{
id: "language_fluency",
name: "语言流畅性",
description: "评估语言表达是否流畅自然",
category: "quality",
isEnabled: true,
},
{
id: "factual_accuracy",
name: "事实准确性",
description: "评估内容中事实信息的准确性",
category: "accuracy",
isEnabled: true,
},
]
export const sliceOperators: SliceOperator[] = [
{
id: "paragraph-split",
name: "段落分割",
description: "按段落自然分割文档",
type: "text",
icon: "📄",
params: { minLength: 50, maxLength: 1000 },
},
{
id: "sentence-split",
name: "句子分割",
description: "按句子边界分割文档",
type: "text",
icon: "📝",
params: { maxSentences: 5, overlap: 1 },
},
{
id: "semantic-split",
name: "语义分割",
description: "基于语义相似度智能分割",
type: "semantic",
icon: "🧠",
params: { threshold: 0.7, windowSize: 3 },
},
{
id: "length-split",
name: "长度分割",
description: "按固定字符长度分割",
type: "text",
icon: "📏",
params: { chunkSize: 512, overlap: 50 },
},
{
id: "structure-split",
name: "结构化分割",
description: "按文档结构(标题、章节)分割",
type: "structure",
icon: "🏗️",
params: { preserveHeaders: true, minSectionLength: 100 },
},
{
id: "table-extract",
name: "表格提取",
description: "提取并单独处理表格内容",
type: "structure",
icon: "📊",
params: { includeHeaders: true, mergeRows: false },
},
{
id: "code-extract",
name: "代码提取",
description: "识别并提取代码块",
type: "custom",
icon: "💻",
params: { languages: ["python", "javascript", "sql"], preserveIndentation: true },
},
{
id: "qa-extract",
name: "问答提取",
description: "自动识别问答格式内容",
type: "semantic",
icon: "❓",
params: { confidenceThreshold: 0.8, generateAnswers: true },
},
]
export const mockTasks: EvaluationTask[] = [
{
id: "1",
name: "客服对话数据质量评估",
datasetId: "1",
datasetName: "客服对话数据集",
evaluationType: "model",
status: "completed",
score: 85,
progress: 100,
createdAt: "2024-01-15 14:30",
completedAt: "2024-01-15 14:45",
description: "评估客服对话数据的质量,包括对话完整性、回复准确性等维度",
dimensions: ["answer_relevance", "content_quality", "information_completeness"],
customDimensions: [],
sliceConfig: {
threshold: 0.8,
sampleCount: 100,
method: "语义分割",
},
modelConfig: {
url: "https://api.openai.com/v1/chat/completions",
apiKey: "sk-***",
prompt: "请从数据质量、标签准确性、标注一致性三个维度评估这个客服对话数据集...",
temperature: 0.3,
maxTokens: 2000,
},
metrics: {
accuracy: 88,
completeness: 92,
consistency: 78,
relevance: 85,
},
issues: [
{ type: "重复数据", count: 23, severity: "medium" },
{ type: "格式错误", count: 5, severity: "high" },
{ type: "内容不完整", count: 12, severity: "low" },
],
},
{
id: "2",
name: "产品评论人工评估",
datasetId: "2",
datasetName: "产品评论数据集",
evaluationType: "manual",
status: "pending",
progress: 0,
createdAt: "2024-01-15 15:20",
description: "人工评估产品评论数据的情感标注准确性",
dimensions: ["content_quality", "factual_accuracy"],
customDimensions: [
{
id: "custom_1",
name: "情感极性准确性",
description: "评估情感标注的极性(正面/负面/中性)准确性",
category: "custom",
isCustom: true,
isEnabled: true,
},
],
sliceConfig: {
threshold: 0.7,
sampleCount: 50,
method: "段落分割",
},
metrics: {
accuracy: 0,
completeness: 0,
consistency: 0,
relevance: 0,
},
issues: [],
},
{
id: "3",
name: "新闻分类数据评估",
datasetId: "4",
datasetName: "新闻分类数据集",
evaluationType: "manual",
status: "running",
progress: 65,
createdAt: "2024-01-15 16:10",
description: "人工评估新闻分类数据集的标注质量",
dimensions: ["content_quality", "information_completeness", "factual_accuracy"],
customDimensions: [],
sliceConfig: {
threshold: 0.9,
sampleCount: 80,
method: "句子分割",
},
metrics: {
accuracy: 82,
completeness: 78,
consistency: 85,
relevance: 80,
},
issues: [{ type: "标注不一致", count: 15, severity: "medium" }],
},
]
// 模拟QA对数据
export const mockQAPairs: QAPair[] = [
{
id: "qa_1",
question: "这个产品的退货政策是什么?",
answer: "我们提供7天无理由退货服务,商品需要保持原包装完整。",
sliceId: "slice_1",
score: 4.5,
feedback: "回答准确且完整",
},
{
id: "qa_2",
question: "如何联系客服?",
answer: "您可以通过在线客服、电话400-123-4567或邮箱service@company.com联系我们。",
sliceId: "slice_2",
score: 5.0,
feedback: "提供了多种联系方式,非常全面",
},
{
id: "qa_3",
question: "配送时间需要多久?",
answer: "一般情况下,我们会在1-3个工作日内发货,配送时间根据地区不同为2-7天。",
sliceId: "slice_3",
score: 4.0,
feedback: "时间范围说明清楚",
},
]
// 评估维度模板配置
export const evaluationTemplates = {
dialogue_text: {
name: "对话文本评估",
dimensions: [
{
id: "answer_relevance",
name: "回答是否有针对性",
description: "评估回答内容是否针对问题,是否切中要点",
category: "accuracy" as const,
isEnabled: true,
},
{
id: "question_correctness",
name: "问题是否正确",
description: "评估问题表述是否清晰、准确、合理",
category: "quality" as const,
isEnabled: true,
},
{
id: "answer_independence",
name: "回答是否独立",
description: "评估回答是否独立完整,不依赖外部信息",
category: "completeness" as const,
isEnabled: true,
},
],
},
data_quality: {
name: "数据质量评估",
dimensions: [
{
id: "data_quality",
name: "数据质量",
description: "评估数据的整体质量,包括格式规范性、完整性等",
category: "quality" as const,
isEnabled: true,
},
{
id: "label_accuracy",
name: "标签准确性",
description: "评估数据标签的准确性和一致性",
category: "accuracy" as const,
isEnabled: true,
},
{
id: "data_completeness",
name: "数据完整性",
description: "评估数据集的完整性,是否存在缺失数据",
category: "completeness" as const,
isEnabled: true,
},
],
},
}

View File

@@ -1,254 +1,254 @@
export const mockChunks = Array.from({ length: 23 }, (_, i) => ({
id: i + 1,
content: `这是第 ${
i + 1
} 个文档分块的内容示例。在实际应用中,这里会显示从原始文档中提取和分割的具体文本内容。用户可以在这里查看和编辑分块的内容,确保知识库的质量和准确性。这个分块包含了重要的业务信息和技术细节,需要仔细维护以确保检索的准确性。`,
position: i + 1,
tokens: Math.floor(Math.random() * 200) + 100,
embedding: Array.from({ length: 1536 }, () => Math.random() - 0.5),
similarity: (Math.random() * 0.3 + 0.7).toFixed(3),
createdAt: "2024-01-22 10:35",
updatedAt: "2024-01-22 10:35",
vectorId: `vec_${i + 1}_${Math.random().toString(36).substr(2, 9)}`,
sliceOperator: ["semantic-split", "paragraph-split", "table-extract"][
Math.floor(Math.random() * 3)
],
parentChunkId: i > 0 ? Math.floor(Math.random() * i) + 1 : undefined,
metadata: {
source: "API文档.pdf",
page: Math.floor(i / 5) + 1,
section: `${Math.floor(i / 3) + 1}`,
},
}));
export const mockQAPairs = [
{
id: 1,
question: "什么是API文档的主要用途?",
answer:
"API文档的主要用途是为开发者提供详细的接口说明,包括请求参数、响应格式和使用示例.",
},
{
id: 2,
question: "如何正确使用这个API?",
answer:
"使用API时需要先获取访问令牌,然后按照文档中的格式发送请求,注意处理错误响应.",
},
];
export const sliceOperators: SliceOperator[] = [
{
id: "paragraph-split",
name: "段落分割",
description: "按段落自然分割文档",
type: "text",
icon: "📄",
params: { minLength: 50, maxLength: 1000 },
},
{
id: "sentence-split",
name: "句子分割",
description: "按句子边界分割文档",
type: "text",
icon: "📝",
params: { maxSentences: 5, overlap: 1 },
},
{
id: "semantic-split",
name: "语义分割",
description: "基于语义相似度智能分割",
type: "semantic",
icon: "🧠",
params: { threshold: 0.7, windowSize: 3 },
},
{
id: "length-split",
name: "长度分割",
description: "按固定字符长度分割",
type: "text",
icon: "📏",
params: { chunkSize: 512, overlap: 50 },
},
{
id: "structure-split",
name: "结构化分割",
description: "按文档结构(标题、章节)分割",
type: "structure",
icon: "🏗️",
params: { preserveHeaders: true, minSectionLength: 100 },
},
{
id: "table-extract",
name: "表格提取",
description: "提取并单独处理表格内容",
type: "structure",
icon: "📊",
params: { includeHeaders: true, mergeRows: false },
},
{
id: "code-extract",
name: "代码提取",
description: "识别并提取代码块",
type: "custom",
icon: "💻",
params: {
languages: ["python", "javascript", "sql"],
preserveIndentation: true,
},
},
{
id: "qa-extract",
name: "问答提取",
description: "自动识别问答格式内容",
type: "semantic",
icon: "❓",
params: { confidenceThreshold: 0.8, generateAnswers: true },
},
];
export const vectorDatabases = [
{
id: "pinecone",
name: "Pinecone",
description: "云端向量数据库,高性能检索",
},
{
id: "weaviate",
name: "Weaviate",
description: "开源向量数据库,支持多模态",
},
{ id: "qdrant", name: "Qdrant", description: "高性能向量搜索引擎" },
{ id: "chroma", name: "ChromaDB", description: "轻量级向量数据库" },
{ id: "milvus", name: "Milvus", description: "分布式向量数据库" },
{ id: "faiss", name: "FAISS", description: "Facebook AI 相似性搜索库" },
];
export const mockKnowledgeBases: KnowledgeBase[] = [
{
id: 1,
name: "产品技术文档库",
description:
"包含所有产品相关的技术文档和API说明,支持多种格式文档的智能解析和向量化处理",
type: "unstructured",
status: "ready",
fileCount: 45,
chunkCount: 1250,
vectorCount: 1250,
size: "2.3 GB",
progress: 100,
createdAt: "2024-01-15",
lastUpdated: "2024-01-22",
vectorDatabase: "pinecone",
config: {
embeddingModel: "text-embedding-3-large",
llmModel: "gpt-4o",
chunkSize: 512,
overlap: 50,
sliceMethod: "semantic",
enableQA: true,
vectorDimension: 1536,
sliceOperators: ["semantic-split", "paragraph-split", "table-extract"],
},
files: [
{
id: 1,
name: "API文档.pdf",
type: "pdf",
size: "2.5 MB",
status: "completed",
chunkCount: 156,
progress: 100,
uploadedAt: "2024-01-15",
source: "upload",
vectorizationStatus: "completed",
},
{
id: 2,
name: "用户手册.docx",
type: "docx",
size: "1.8 MB",
status: "disabled",
chunkCount: 89,
progress: 65,
uploadedAt: "2024-01-22",
source: "dataset",
datasetId: "dataset-1",
vectorizationStatus: "failed",
},
],
vectorizationHistory: [
{
id: 1,
timestamp: "2024-01-22 14:30:00",
operation: "create",
fileId: 1,
fileName: "API文档.pdf",
chunksProcessed: 156,
vectorsGenerated: 156,
status: "success",
duration: "2m 15s",
config: {
embeddingModel: "text-embedding-3-large",
chunkSize: 512,
sliceMethod: "semantic",
},
},
{
id: 2,
timestamp: "2024-01-22 15:45:00",
operation: "update",
fileId: 2,
fileName: "用户手册.docx",
chunksProcessed: 89,
vectorsGenerated: 0,
status: "failed",
duration: "0m 45s",
config: {
embeddingModel: "text-embedding-3-large",
chunkSize: 512,
sliceMethod: "semantic",
},
error: "向量化服务连接超时",
},
],
},
{
id: 2,
name: "FAQ结构化知识库",
description: "客服常见问题的结构化问答对,支持快速检索和智能匹配",
type: "structured",
status: "vectorizing",
fileCount: 12,
chunkCount: 890,
vectorCount: 750,
size: "156 MB",
progress: 75,
createdAt: "2024-01-20",
lastUpdated: "2024-01-23",
vectorDatabase: "weaviate",
config: {
embeddingModel: "text-embedding-ada-002",
chunkSize: 256,
overlap: 0,
sliceMethod: "paragraph",
enableQA: false,
vectorDimension: 1536,
sliceOperators: ["qa-extract", "paragraph-split"],
},
files: [
{
id: 3,
name: "FAQ模板.xlsx",
type: "xlsx",
size: "450 KB",
status: "vectorizing",
chunkCount: 234,
progress: 75,
uploadedAt: "2024-01-20",
source: "upload",
vectorizationStatus: "processing",
},
],
vectorizationHistory: [],
},
];
export const mockChunks = Array.from({ length: 23 }, (_, i) => ({
id: i + 1,
content: `这是第 ${
i + 1
} 个文档分块的内容示例。在实际应用中,这里会显示从原始文档中提取和分割的具体文本内容。用户可以在这里查看和编辑分块的内容,确保知识库的质量和准确性。这个分块包含了重要的业务信息和技术细节,需要仔细维护以确保检索的准确性。`,
position: i + 1,
tokens: Math.floor(Math.random() * 200) + 100,
embedding: Array.from({ length: 1536 }, () => Math.random() - 0.5),
similarity: (Math.random() * 0.3 + 0.7).toFixed(3),
createdAt: "2024-01-22 10:35",
updatedAt: "2024-01-22 10:35",
vectorId: `vec_${i + 1}_${Math.random().toString(36).substr(2, 9)}`,
sliceOperator: ["semantic-split", "paragraph-split", "table-extract"][
Math.floor(Math.random() * 3)
],
parentChunkId: i > 0 ? Math.floor(Math.random() * i) + 1 : undefined,
metadata: {
source: "API文档.pdf",
page: Math.floor(i / 5) + 1,
section: `${Math.floor(i / 3) + 1}`,
},
}));
export const mockQAPairs = [
{
id: 1,
question: "什么是API文档的主要用途?",
answer:
"API文档的主要用途是为开发者提供详细的接口说明,包括请求参数、响应格式和使用示例.",
},
{
id: 2,
question: "如何正确使用这个API?",
answer:
"使用API时需要先获取访问令牌,然后按照文档中的格式发送请求,注意处理错误响应.",
},
];
export const sliceOperators: SliceOperator[] = [
{
id: "paragraph-split",
name: "段落分割",
description: "按段落自然分割文档",
type: "text",
icon: "📄",
params: { minLength: 50, maxLength: 1000 },
},
{
id: "sentence-split",
name: "句子分割",
description: "按句子边界分割文档",
type: "text",
icon: "📝",
params: { maxSentences: 5, overlap: 1 },
},
{
id: "semantic-split",
name: "语义分割",
description: "基于语义相似度智能分割",
type: "semantic",
icon: "🧠",
params: { threshold: 0.7, windowSize: 3 },
},
{
id: "length-split",
name: "长度分割",
description: "按固定字符长度分割",
type: "text",
icon: "📏",
params: { chunkSize: 512, overlap: 50 },
},
{
id: "structure-split",
name: "结构化分割",
description: "按文档结构(标题、章节)分割",
type: "structure",
icon: "🏗️",
params: { preserveHeaders: true, minSectionLength: 100 },
},
{
id: "table-extract",
name: "表格提取",
description: "提取并单独处理表格内容",
type: "structure",
icon: "📊",
params: { includeHeaders: true, mergeRows: false },
},
{
id: "code-extract",
name: "代码提取",
description: "识别并提取代码块",
type: "custom",
icon: "💻",
params: {
languages: ["python", "javascript", "sql"],
preserveIndentation: true,
},
},
{
id: "qa-extract",
name: "问答提取",
description: "自动识别问答格式内容",
type: "semantic",
icon: "❓",
params: { confidenceThreshold: 0.8, generateAnswers: true },
},
];
export const vectorDatabases = [
{
id: "pinecone",
name: "Pinecone",
description: "云端向量数据库,高性能检索",
},
{
id: "weaviate",
name: "Weaviate",
description: "开源向量数据库,支持多模态",
},
{ id: "qdrant", name: "Qdrant", description: "高性能向量搜索引擎" },
{ id: "chroma", name: "ChromaDB", description: "轻量级向量数据库" },
{ id: "milvus", name: "Milvus", description: "分布式向量数据库" },
{ id: "faiss", name: "FAISS", description: "Facebook AI 相似性搜索库" },
];
export const mockKnowledgeBases: KnowledgeBase[] = [
{
id: 1,
name: "产品技术文档库",
description:
"包含所有产品相关的技术文档和API说明,支持多种格式文档的智能解析和向量化处理",
type: "unstructured",
status: "ready",
fileCount: 45,
chunkCount: 1250,
vectorCount: 1250,
size: "2.3 GB",
progress: 100,
createdAt: "2024-01-15",
lastUpdated: "2024-01-22",
vectorDatabase: "pinecone",
config: {
embeddingModel: "text-embedding-3-large",
llmModel: "gpt-4o",
chunkSize: 512,
overlap: 50,
sliceMethod: "semantic",
enableQA: true,
vectorDimension: 1536,
sliceOperators: ["semantic-split", "paragraph-split", "table-extract"],
},
files: [
{
id: 1,
name: "API文档.pdf",
type: "pdf",
size: "2.5 MB",
status: "completed",
chunkCount: 156,
progress: 100,
uploadedAt: "2024-01-15",
source: "upload",
vectorizationStatus: "completed",
},
{
id: 2,
name: "用户手册.docx",
type: "docx",
size: "1.8 MB",
status: "disabled",
chunkCount: 89,
progress: 65,
uploadedAt: "2024-01-22",
source: "dataset",
datasetId: "dataset-1",
vectorizationStatus: "failed",
},
],
vectorizationHistory: [
{
id: 1,
timestamp: "2024-01-22 14:30:00",
operation: "create",
fileId: 1,
fileName: "API文档.pdf",
chunksProcessed: 156,
vectorsGenerated: 156,
status: "success",
duration: "2m 15s",
config: {
embeddingModel: "text-embedding-3-large",
chunkSize: 512,
sliceMethod: "semantic",
},
},
{
id: 2,
timestamp: "2024-01-22 15:45:00",
operation: "update",
fileId: 2,
fileName: "用户手册.docx",
chunksProcessed: 89,
vectorsGenerated: 0,
status: "failed",
duration: "0m 45s",
config: {
embeddingModel: "text-embedding-3-large",
chunkSize: 512,
sliceMethod: "semantic",
},
error: "向量化服务连接超时",
},
],
},
{
id: 2,
name: "FAQ结构化知识库",
description: "客服常见问题的结构化问答对,支持快速检索和智能匹配",
type: "structured",
status: "vectorizing",
fileCount: 12,
chunkCount: 890,
vectorCount: 750,
size: "156 MB",
progress: 75,
createdAt: "2024-01-20",
lastUpdated: "2024-01-23",
vectorDatabase: "weaviate",
config: {
embeddingModel: "text-embedding-ada-002",
chunkSize: 256,
overlap: 0,
sliceMethod: "paragraph",
enableQA: false,
vectorDimension: 1536,
sliceOperators: ["qa-extract", "paragraph-split"],
},
files: [
{
id: 3,
name: "FAQ模板.xlsx",
type: "xlsx",
size: "450 KB",
status: "vectorizing",
chunkCount: 234,
progress: 75,
uploadedAt: "2024-01-20",
source: "upload",
vectorizationStatus: "processing",
},
],
vectorizationHistory: [],
},
];

View File

@@ -1,167 +1,167 @@
const { addMockPrefix } = require("./mock-core/util.cjs");
const MockAPI = {
// 数据归集接口
queryTasksUsingGet: "/data-collection/tasks", // 获取数据源任务列表
createTaskUsingPost: "/data-collection/tasks", // 创建数据源任务
queryTaskByIdUsingGet: "/data-collection/tasks/:id", // 根据ID获取数据源任务详情
updateTaskByIdUsingPut: "/data-collection/tasks/:id", // 更新数据源任务
queryDataXTemplatesUsingGet: "/data-collection/templates", // 获取DataX数据源模板列表
deleteTaskByIdUsingDelete: "/data-collection/tasks/:id", // 删除数据源任务
executeTaskByIdUsingPost: "/data-collection/tasks/:id/execute", // 执行数据源任务
stopTaskByIdUsingPost: "/data-collection/tasks/:id/stop", // 停止数据源任务
queryExecutionLogUsingPost: "/data-collection/executions", // 获取任务执行日志
queryExecutionLogByIdUsingGet: "/data-collection/executions/:id", // 获取任务执行日志详情
queryCollectionStatisticsUsingGet: "/data-collection/monitor/statistics", // 获取数据归集统计信息
// 数据管理接口
queryDatasetsUsingGet: "/data-management/datasets", // 获取数据集列表
createDatasetUsingPost: "/data-management/datasets", // 创建数据集
queryDatasetByIdUsingGet: "/data-management/datasets/:id", // 根据ID获取数据集详情
updateDatasetByIdUsingPut: "/data-management/datasets/:id", // 更新数据集
deleteDatasetByIdUsingDelete: "/data-management/datasets/:id", // 删除数据集
queryFilesUsingGet: "/data-management/datasets/:id/files", // 获取数据集文件列表
uploadFileUsingPost: "/data-management/datasets/:id/files", // 添加数据集文件
queryFileByIdUsingGet: "/data-management/datasets/:id/files/:fileId", // 获取数据集文件详情
deleteFileByIdUsingDelete: "/data-management/datasets/:id/files/:fileId", // 删除数据集文件
downloadFileByIdUsingGet:
"/data-management/datasets/:id/files/:fileId/download", // 下载文件
queryDatasetTypesUsingGet: "/data-management/dataset-types", // 获取数据集类型列表
queryTagsUsingGet: "/data-management/tags", // 获取数据集标签列表
createTagUsingPost: "/data-management/tags", // 创建数据集标签
updateTagUsingPost: "/data-management/tags", // 更新数据集标签
deleteTagUsingPost: "/data-management/tags", // 删除数据集标签
queryDatasetStatisticsUsingGet: "/data-management/datasets/statistics", // 获取数据集统计信息
preUploadFileUsingPost: "/data-management/datasets/:id/upload/pre-upload", // 预上传文件
cancelUploadUsingPut: "/data-management/datasets/upload/cancel-upload/:id", // 取消上传
uploadFileChunkUsingPost: "/data-management/datasets/:id/upload/chunk", // 上传切片
// 数据清洗接口
queryCleaningTasksUsingGet: "/cleaning/tasks", // 获取清洗任务列表
createCleaningTaskUsingPost: "/cleaning/tasks", // 创建清洗任务
queryCleaningTaskByIdUsingGet: "/cleaning/tasks/:taskId", // 根据ID获取清洗任务详情
deleteCleaningTaskByIdUsingDelete: "/cleaning/tasks/:taskId", // 删除清洗任务
executeCleaningTaskUsingPost: "/cleaning/tasks/:taskId/execute", // 执行清洗任务
stopCleaningTaskUsingPost: "/cleaning/tasks/:taskId/stop", // 停止清洗任务
queryCleaningTemplatesUsingGet: "/cleaning/templates", // 获取清洗模板列表
createCleaningTemplateUsingPost: "/cleaning/templates", // 创建清洗模板
queryCleaningTemplateByIdUsingGet: "/cleaning/templates/:templateId", // 根据ID获取清洗模板详情
updateCleaningTemplateByIdUsingPut: "/cleaning/templates/:templateId", // 根据ID更新清洗模板详情
deleteCleaningTemplateByIdUsingDelete: "/cleaning/templates/:templateId", // 删除清洗模板
// 数据标注接口
queryAnnotationTasksUsingGet: "/project/mappings/list", // 获取标注任务列表
createAnnotationTaskUsingPost: "/project/create", // 创建标注任务
syncAnnotationTaskByIdUsingPost: "/project/sync", // 同步标注任务
deleteAnnotationTaskByIdUsingDelete: "/project/mappings", // 删除标注任务
queryAnnotationTaskByIdUsingGet: "/annotation/tasks/:taskId", // 根据ID获取标注任务详情
executeAnnotationTaskByIdUsingPost: "/annotation/tasks/:taskId/execute", // 执行标注任务
stopAnnotationTaskByIdUsingPost: "/annotation/tasks/:taskId/stop", // 停止标注任务
queryAnnotationDataUsingGet: "/annotation/data", // 获取标注数据列表
submitAnnotationUsingPost: "/annotation/submit/:id", // 提交标注
updateAnnotationUsingPut: "/annotation/update/:id", // 根据ID更新标注
deleteAnnotationUsingDelete: "/annotation/delete/:id", // 根据ID删除标注
startAnnotationTaskUsingPost: "/annotation/start/:taskId", // 开始标注任务
pauseAnnotationTaskUsingPost: "/annotation/pause/:taskId", // 暂停标注任务
resumeAnnotationTaskUsingPost: "/annotation/resume/:taskId", // 恢复标注任务
completeAnnotationTaskUsingPost: "/annotation/complete/:taskId", // 完成标注任务
getAnnotationTaskStatisticsUsingGet: "/annotation/statistics/:taskId", // 获取标注任务统计信息
getAnnotationStatisticsUsingGet: "/annotation/statistics", // 获取标注统计信息
queryAnnotationTemplatesUsingGet: "/annotation/templates", // 获取标注模板列表
createAnnotationTemplateUsingPost: "/annotation/templates", // 创建标注模板
queryAnnotationTemplateByIdUsingGet: "/annotation/templates/:templateId", // 根据ID获取标注模板详情
queryAnnotatorsUsingGet: "/annotation/annotators", // 获取标注者列表
assignAnnotatorUsingPost: "/annotation/annotators/:annotatorId", // 分配标注者
// 数据合成接口
querySynthesisJobsUsingGet: "/synthesis/jobs", // 获取合成任务列表
createSynthesisJobUsingPost: "/synthesis/jobs/create", // 创建合成任务
querySynthesisJobByIdUsingGet: "/synthesis/jobs/:jobId", // 根据ID获取合成任务详情
updateSynthesisJobByIdUsingPut: "/synthesis/jobs/:jobId", // 更新合成任务
deleteSynthesisJobByIdUsingDelete: "/synthesis/jobs/:jobId", // 删除合成任务
executeSynthesisJobUsingPost: "/synthesis/jobs/execute/:jobId", // 执行合成任务
stopSynthesisJobByIdUsingPost: "/synthesis/jobs/stop/:jobId", // 停止合成任务
querySynthesisTemplatesUsingGet: "/synthesis/templates", // 获取合成模板列表
createSynthesisTemplateUsingPost: "/synthesis/templates/create", // 创建合成模板
querySynthesisTemplateByIdUsingGet: "/synthesis/templates/:templateId", // 根据ID获取合成模板详情
updateSynthesisTemplateByIdUsingPut: "/synthesis/templates/:templateId", // 更新合成模板
deleteSynthesisTemplateByIdUsingDelete: "/synthesis/templates/:templateId", // 删除合成模板
queryInstructionTemplatesUsingPost: "/synthesis/templates", // 获取指令模板列表
createInstructionTemplateUsingPost: "/synthesis/templates/create", // 创建指令模板
queryInstructionTemplateByIdUsingGet: "/synthesis/templates/:templateId", // 根据ID获取指令模板详情
deleteInstructionTemplateByIdUsingDelete: "/synthesis/templates/:templateId", // 删除指令模板
instructionTuningUsingPost: "/synthesis/instruction-tuning", // 指令微调
cotDistillationUsingPost: "/synthesis/cot-distillation", // Cot蒸馏
// 数据配比接口
createRatioTaskUsingPost: "/synthesis/ratio-task", // 创建配比任务
queryRatioTasksUsingGet: "/synthesis/ratio-task", // 获取配比任务列表
queryRatioTaskByIdUsingGet: "/synthesis/ratio-task/:taskId", // 根据ID获取配比任务详情
deleteRatioTaskByIdUsingDelete: "/synthesis/ratio-task/:taskId", // 删除配比任务
updateRatioTaskByIdUsingPut: "/synthesis/ratio-task/:taskId", // 更新配比任务
executeRatioTaskByIdUsingPost: "/synthesis/ratio-task/:taskId/execute", // 执行配比任务
stopRatioTaskByIdUsingPost: "/synthesis/ratio-task/:taskId/stop", // 停止配比任务
queryRatioJobStatusUsingGet: "/synthesis/ratio-task/:taskId/status", // 获取配比任务状态
queryRatioModelsUsingGet: "/synthesis/ratio-models", // 获取配比模型列表
// 数据评测接口
queryEvaluationTasksUsingPost: "/evaluation/tasks", // 获取评测任务列表
createEvaluationTaskUsingPost: "/evaluation/tasks/create", // 创建评测任务
queryEvaluationTaskByIdUsingGet: "/evaluation/tasks/:taskId", // 根据ID获取评测任务详情
updateEvaluationTaskByIdUsingPut: "/evaluation/tasks/:taskId", // 更新评测任务
deleteEvaluationTaskByIdUsingDelete: "/evaluation/tasks/:taskId", // 删除评测任务
executeEvaluationTaskByIdUsingPost: "/evaluation/tasks/:taskId/execute", // 执行评测任务
stopEvaluationTaskByIdUsingPost: "/evaluation/tasks/:taskId/stop", // 停止评测任务
queryEvaluationReportsUsingPost: "/evaluation/reports", // 获取评测报告列表
queryEvaluationReportByIdUsingGet: "/evaluation/reports/:reportId", // 根据ID获取评测报告详情
manualEvaluateUsingPost: "/evaluation/manual-evaluate", // 人工评测
queryEvaluationStatisticsUsingGet: "/evaluation/statistics", // 获取评测统计信息
evaluateDataQualityUsingPost: "/evaluation/data-quality", // 数据质量评测
getQualityEvaluationByIdUsingGet: "/evaluation/data-quality/:id", // 根据ID获取数据质量评测详情
evaluateCompatibilityUsingPost: "/evaluation/compatibility", // 兼容性评测
evaluateValueUsingPost: "/evaluation/value", // 价值评测
queryEvaluationReportsUsingGet: "/evaluation/reports", // 获取评测报告列表(简化版)
getEvaluationReportByIdUsingGet: "/evaluation/reports/:reportId", // 根据ID获取评测报告详情(简化版)
exportEvaluationReportUsingGet: "/evaluation/reports/:reportId/export", // 导出评测报告
batchEvaluationUsingPost: "/evaluation/batch-evaluate", // 批量评测
// 知识生成接口
queryKnowledgeBasesUsingPost: "/knowledge-base/list", // 获取知识库列表
createKnowledgeBaseUsingPost: "/knowledge-base/create", // 创建知识库
queryKnowledgeBaseByIdUsingGet: "/knowledge-base/:baseId", // 根据ID获取知识库详情
updateKnowledgeBaseByIdUsingPut: "/knowledge-base/:baseId", // 更新知识库
deleteKnowledgeBaseByIdUsingDelete: "/knowledge-base/:baseId", // 删除知识库
addKnowledgeBaseFilesUsingPost: "/knowledge-base/:baseId/files", // 添加文件到知识库
queryKnowledgeBaseFilesGet: "/knowledge-base/:baseId/files", // 根据ID获取知识生成文件列表
queryKnowledgeBaseFilesByIdUsingGet:
"/knowledge-base/:baseId/files/:fileId", // 根据ID获取知识生成文件详情
deleteKnowledgeBaseTaskByIdUsingDelete: "/knowledge-base/:baseId/files/:id", // 删除知识生成文件
// 算子市场
queryOperatorsUsingPost: "/operators/list", // 获取算子列表
queryCategoryTreeUsingGet: "/categories/tree", // 获取算子分类树
queryOperatorByIdUsingGet: "/operators/:id", // 根据ID获取算子详情
createOperatorUsingPost: "/operators/create", // 创建算子
updateOperatorByIdUsingPut: "/operators/:id", // 更新算子
uploadOperatorUsingPost: "/operators/upload", // 上传算子
uploadFileChunkUsingPost: "/operators/upload/chunk", // 上传切片
preUploadOperatorUsingPost: "/operators/upload/pre-upload", // 预上传文件
cancelUploadOperatorUsingPut: "/operators/upload/cancel-upload", // 取消上传
createLabelUsingPost: "/operators/labels", // 创建算子标签
queryLabelsUsingGet: "/labels", // 获取算子标签列表
deleteLabelsUsingDelete: "/labels", // 删除算子标签
updateLabelByIdUsingPut: "/labels/:labelId", // 更新算子标签
deleteOperatorByIdUsingDelete: "/operators/:operatorId", // 删除算子
publishOperatorUsingPost: "/operators/:operatorId/publish", // 发布算子
unpublishOperatorUsingPost: "/operators/:operatorId/unpublish", // 下架算子
// 设置接口
queryModelsUsingGet: "/models/list", // 获取模型列表
queryProvidersUsingGet: "/models/providers", // 获取模型提供商列表
createModelUsingPost: "/models/create", // 创建模型
updateModelUsingPut: "/models/:id", // 更新模型
deleteModelUsingDelete: "/models/:id", // 删除模型
};
module.exports = addMockPrefix("/api", MockAPI);
const { addMockPrefix } = require("./mock-core/util.cjs");
const MockAPI = {
// 数据归集接口
queryTasksUsingGet: "/data-collection/tasks", // 获取数据源任务列表
createTaskUsingPost: "/data-collection/tasks", // 创建数据源任务
queryTaskByIdUsingGet: "/data-collection/tasks/:id", // 根据ID获取数据源任务详情
updateTaskByIdUsingPut: "/data-collection/tasks/:id", // 更新数据源任务
queryDataXTemplatesUsingGet: "/data-collection/templates", // 获取DataX数据源模板列表
deleteTaskByIdUsingDelete: "/data-collection/tasks/:id", // 删除数据源任务
executeTaskByIdUsingPost: "/data-collection/tasks/:id/execute", // 执行数据源任务
stopTaskByIdUsingPost: "/data-collection/tasks/:id/stop", // 停止数据源任务
queryExecutionLogUsingPost: "/data-collection/executions", // 获取任务执行日志
queryExecutionLogByIdUsingGet: "/data-collection/executions/:id", // 获取任务执行日志详情
queryCollectionStatisticsUsingGet: "/data-collection/monitor/statistics", // 获取数据归集统计信息
// 数据管理接口
queryDatasetsUsingGet: "/data-management/datasets", // 获取数据集列表
createDatasetUsingPost: "/data-management/datasets", // 创建数据集
queryDatasetByIdUsingGet: "/data-management/datasets/:id", // 根据ID获取数据集详情
updateDatasetByIdUsingPut: "/data-management/datasets/:id", // 更新数据集
deleteDatasetByIdUsingDelete: "/data-management/datasets/:id", // 删除数据集
queryFilesUsingGet: "/data-management/datasets/:id/files", // 获取数据集文件列表
uploadFileUsingPost: "/data-management/datasets/:id/files", // 添加数据集文件
queryFileByIdUsingGet: "/data-management/datasets/:id/files/:fileId", // 获取数据集文件详情
deleteFileByIdUsingDelete: "/data-management/datasets/:id/files/:fileId", // 删除数据集文件
downloadFileByIdUsingGet:
"/data-management/datasets/:id/files/:fileId/download", // 下载文件
queryDatasetTypesUsingGet: "/data-management/dataset-types", // 获取数据集类型列表
queryTagsUsingGet: "/data-management/tags", // 获取数据集标签列表
createTagUsingPost: "/data-management/tags", // 创建数据集标签
updateTagUsingPost: "/data-management/tags", // 更新数据集标签
deleteTagUsingPost: "/data-management/tags", // 删除数据集标签
queryDatasetStatisticsUsingGet: "/data-management/datasets/statistics", // 获取数据集统计信息
preUploadFileUsingPost: "/data-management/datasets/:id/upload/pre-upload", // 预上传文件
cancelUploadUsingPut: "/data-management/datasets/upload/cancel-upload/:id", // 取消上传
uploadFileChunkUsingPost: "/data-management/datasets/:id/upload/chunk", // 上传切片
// 数据清洗接口
queryCleaningTasksUsingGet: "/cleaning/tasks", // 获取清洗任务列表
createCleaningTaskUsingPost: "/cleaning/tasks", // 创建清洗任务
queryCleaningTaskByIdUsingGet: "/cleaning/tasks/:taskId", // 根据ID获取清洗任务详情
deleteCleaningTaskByIdUsingDelete: "/cleaning/tasks/:taskId", // 删除清洗任务
executeCleaningTaskUsingPost: "/cleaning/tasks/:taskId/execute", // 执行清洗任务
stopCleaningTaskUsingPost: "/cleaning/tasks/:taskId/stop", // 停止清洗任务
queryCleaningTemplatesUsingGet: "/cleaning/templates", // 获取清洗模板列表
createCleaningTemplateUsingPost: "/cleaning/templates", // 创建清洗模板
queryCleaningTemplateByIdUsingGet: "/cleaning/templates/:templateId", // 根据ID获取清洗模板详情
updateCleaningTemplateByIdUsingPut: "/cleaning/templates/:templateId", // 根据ID更新清洗模板详情
deleteCleaningTemplateByIdUsingDelete: "/cleaning/templates/:templateId", // 删除清洗模板
// 数据标注接口
queryAnnotationTasksUsingGet: "/project/mappings/list", // 获取标注任务列表
createAnnotationTaskUsingPost: "/project/create", // 创建标注任务
syncAnnotationTaskByIdUsingPost: "/project/sync", // 同步标注任务
deleteAnnotationTaskByIdUsingDelete: "/project/mappings", // 删除标注任务
queryAnnotationTaskByIdUsingGet: "/annotation/tasks/:taskId", // 根据ID获取标注任务详情
executeAnnotationTaskByIdUsingPost: "/annotation/tasks/:taskId/execute", // 执行标注任务
stopAnnotationTaskByIdUsingPost: "/annotation/tasks/:taskId/stop", // 停止标注任务
queryAnnotationDataUsingGet: "/annotation/data", // 获取标注数据列表
submitAnnotationUsingPost: "/annotation/submit/:id", // 提交标注
updateAnnotationUsingPut: "/annotation/update/:id", // 根据ID更新标注
deleteAnnotationUsingDelete: "/annotation/delete/:id", // 根据ID删除标注
startAnnotationTaskUsingPost: "/annotation/start/:taskId", // 开始标注任务
pauseAnnotationTaskUsingPost: "/annotation/pause/:taskId", // 暂停标注任务
resumeAnnotationTaskUsingPost: "/annotation/resume/:taskId", // 恢复标注任务
completeAnnotationTaskUsingPost: "/annotation/complete/:taskId", // 完成标注任务
getAnnotationTaskStatisticsUsingGet: "/annotation/statistics/:taskId", // 获取标注任务统计信息
getAnnotationStatisticsUsingGet: "/annotation/statistics", // 获取标注统计信息
queryAnnotationTemplatesUsingGet: "/annotation/templates", // 获取标注模板列表
createAnnotationTemplateUsingPost: "/annotation/templates", // 创建标注模板
queryAnnotationTemplateByIdUsingGet: "/annotation/templates/:templateId", // 根据ID获取标注模板详情
queryAnnotatorsUsingGet: "/annotation/annotators", // 获取标注者列表
assignAnnotatorUsingPost: "/annotation/annotators/:annotatorId", // 分配标注者
// 数据合成接口
querySynthesisJobsUsingGet: "/synthesis/jobs", // 获取合成任务列表
createSynthesisJobUsingPost: "/synthesis/jobs/create", // 创建合成任务
querySynthesisJobByIdUsingGet: "/synthesis/jobs/:jobId", // 根据ID获取合成任务详情
updateSynthesisJobByIdUsingPut: "/synthesis/jobs/:jobId", // 更新合成任务
deleteSynthesisJobByIdUsingDelete: "/synthesis/jobs/:jobId", // 删除合成任务
executeSynthesisJobUsingPost: "/synthesis/jobs/execute/:jobId", // 执行合成任务
stopSynthesisJobByIdUsingPost: "/synthesis/jobs/stop/:jobId", // 停止合成任务
querySynthesisTemplatesUsingGet: "/synthesis/templates", // 获取合成模板列表
createSynthesisTemplateUsingPost: "/synthesis/templates/create", // 创建合成模板
querySynthesisTemplateByIdUsingGet: "/synthesis/templates/:templateId", // 根据ID获取合成模板详情
updateSynthesisTemplateByIdUsingPut: "/synthesis/templates/:templateId", // 更新合成模板
deleteSynthesisTemplateByIdUsingDelete: "/synthesis/templates/:templateId", // 删除合成模板
queryInstructionTemplatesUsingPost: "/synthesis/templates", // 获取指令模板列表
createInstructionTemplateUsingPost: "/synthesis/templates/create", // 创建指令模板
queryInstructionTemplateByIdUsingGet: "/synthesis/templates/:templateId", // 根据ID获取指令模板详情
deleteInstructionTemplateByIdUsingDelete: "/synthesis/templates/:templateId", // 删除指令模板
instructionTuningUsingPost: "/synthesis/instruction-tuning", // 指令微调
cotDistillationUsingPost: "/synthesis/cot-distillation", // Cot蒸馏
// 数据配比接口
createRatioTaskUsingPost: "/synthesis/ratio-task", // 创建配比任务
queryRatioTasksUsingGet: "/synthesis/ratio-task", // 获取配比任务列表
queryRatioTaskByIdUsingGet: "/synthesis/ratio-task/:taskId", // 根据ID获取配比任务详情
deleteRatioTaskByIdUsingDelete: "/synthesis/ratio-task/:taskId", // 删除配比任务
updateRatioTaskByIdUsingPut: "/synthesis/ratio-task/:taskId", // 更新配比任务
executeRatioTaskByIdUsingPost: "/synthesis/ratio-task/:taskId/execute", // 执行配比任务
stopRatioTaskByIdUsingPost: "/synthesis/ratio-task/:taskId/stop", // 停止配比任务
queryRatioJobStatusUsingGet: "/synthesis/ratio-task/:taskId/status", // 获取配比任务状态
queryRatioModelsUsingGet: "/synthesis/ratio-models", // 获取配比模型列表
// 数据评测接口
queryEvaluationTasksUsingPost: "/evaluation/tasks", // 获取评测任务列表
createEvaluationTaskUsingPost: "/evaluation/tasks/create", // 创建评测任务
queryEvaluationTaskByIdUsingGet: "/evaluation/tasks/:taskId", // 根据ID获取评测任务详情
updateEvaluationTaskByIdUsingPut: "/evaluation/tasks/:taskId", // 更新评测任务
deleteEvaluationTaskByIdUsingDelete: "/evaluation/tasks/:taskId", // 删除评测任务
executeEvaluationTaskByIdUsingPost: "/evaluation/tasks/:taskId/execute", // 执行评测任务
stopEvaluationTaskByIdUsingPost: "/evaluation/tasks/:taskId/stop", // 停止评测任务
queryEvaluationReportsUsingPost: "/evaluation/reports", // 获取评测报告列表
queryEvaluationReportByIdUsingGet: "/evaluation/reports/:reportId", // 根据ID获取评测报告详情
manualEvaluateUsingPost: "/evaluation/manual-evaluate", // 人工评测
queryEvaluationStatisticsUsingGet: "/evaluation/statistics", // 获取评测统计信息
evaluateDataQualityUsingPost: "/evaluation/data-quality", // 数据质量评测
getQualityEvaluationByIdUsingGet: "/evaluation/data-quality/:id", // 根据ID获取数据质量评测详情
evaluateCompatibilityUsingPost: "/evaluation/compatibility", // 兼容性评测
evaluateValueUsingPost: "/evaluation/value", // 价值评测
queryEvaluationReportsUsingGet: "/evaluation/reports", // 获取评测报告列表(简化版)
getEvaluationReportByIdUsingGet: "/evaluation/reports/:reportId", // 根据ID获取评测报告详情(简化版)
exportEvaluationReportUsingGet: "/evaluation/reports/:reportId/export", // 导出评测报告
batchEvaluationUsingPost: "/evaluation/batch-evaluate", // 批量评测
// 知识生成接口
queryKnowledgeBasesUsingPost: "/knowledge-base/list", // 获取知识库列表
createKnowledgeBaseUsingPost: "/knowledge-base/create", // 创建知识库
queryKnowledgeBaseByIdUsingGet: "/knowledge-base/:baseId", // 根据ID获取知识库详情
updateKnowledgeBaseByIdUsingPut: "/knowledge-base/:baseId", // 更新知识库
deleteKnowledgeBaseByIdUsingDelete: "/knowledge-base/:baseId", // 删除知识库
addKnowledgeBaseFilesUsingPost: "/knowledge-base/:baseId/files", // 添加文件到知识库
queryKnowledgeBaseFilesGet: "/knowledge-base/:baseId/files", // 根据ID获取知识生成文件列表
queryKnowledgeBaseFilesByIdUsingGet:
"/knowledge-base/:baseId/files/:fileId", // 根据ID获取知识生成文件详情
deleteKnowledgeBaseTaskByIdUsingDelete: "/knowledge-base/:baseId/files/:id", // 删除知识生成文件
// 算子市场
queryOperatorsUsingPost: "/operators/list", // 获取算子列表
queryCategoryTreeUsingGet: "/categories/tree", // 获取算子分类树
queryOperatorByIdUsingGet: "/operators/:id", // 根据ID获取算子详情
createOperatorUsingPost: "/operators/create", // 创建算子
updateOperatorByIdUsingPut: "/operators/:id", // 更新算子
uploadOperatorUsingPost: "/operators/upload", // 上传算子
uploadFileChunkUsingPost: "/operators/upload/chunk", // 上传切片
preUploadOperatorUsingPost: "/operators/upload/pre-upload", // 预上传文件
cancelUploadOperatorUsingPut: "/operators/upload/cancel-upload", // 取消上传
createLabelUsingPost: "/operators/labels", // 创建算子标签
queryLabelsUsingGet: "/labels", // 获取算子标签列表
deleteLabelsUsingDelete: "/labels", // 删除算子标签
updateLabelByIdUsingPut: "/labels/:labelId", // 更新算子标签
deleteOperatorByIdUsingDelete: "/operators/:operatorId", // 删除算子
publishOperatorUsingPost: "/operators/:operatorId/publish", // 发布算子
unpublishOperatorUsingPost: "/operators/:operatorId/unpublish", // 下架算子
// 设置接口
queryModelsUsingGet: "/models/list", // 获取模型列表
queryProvidersUsingGet: "/models/providers", // 获取模型提供商列表
createModelUsingPost: "/models/create", // 创建模型
updateModelUsingPut: "/models/:id", // 更新模型
deleteModelUsingDelete: "/models/:id", // 删除模型
};
module.exports = addMockPrefix("/api", MockAPI);

View File

@@ -1,25 +1,25 @@
const fs = require('fs');
function loadAllMockModules(router, pathDir) {
if (!fs.existsSync(pathDir)) {
throw new Error(`Mock directory ${pathDir} does not exist.`);
}
const files = fs.readdirSync(pathDir);
files.forEach(file => {
const filePath = `${pathDir}/${file}`;
if(fs.lstatSync(filePath).isDirectory()) {
loadAllMockModules(router, filePath);
} else {
let fileNameModule = file.replace('/\.js\b$/', '');
let module = require(`${pathDir}/${fileNameModule}`);
if(typeof module === 'function' && module.length === 1) {
module(router);
}
}
});
}
module.exports = {
loadAllMockModules,
const fs = require('fs');
function loadAllMockModules(router, pathDir) {
if (!fs.existsSync(pathDir)) {
throw new Error(`Mock directory ${pathDir} does not exist.`);
}
const files = fs.readdirSync(pathDir);
files.forEach(file => {
const filePath = `${pathDir}/${file}`;
if(fs.lstatSync(filePath).isDirectory()) {
loadAllMockModules(router, filePath);
} else {
let fileNameModule = file.replace('/\.js\b$/', '');
let module = require(`${pathDir}/${fileNameModule}`);
if(typeof module === 'function' && module.length === 1) {
module(router);
}
}
});
}
module.exports = {
loadAllMockModules,
};

View File

@@ -1,63 +1,63 @@
const path = require("path");
const Mock = require("mockjs");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const { isFunction } = require("lodash");
const argv = require("minimist")(process.argv.slice(2));
const isDev = (argv.env || "development") === "development";
const TOKEN_KEY = isDev ? "X-Auth-Token" : "X-Csrf-Token";
const setSessionUser = (req, getLoginInfo) => {
if (!isFunction(getLoginInfo)) {
throw new Error("getLoginInfo must be a function");
}
if (!req.session?.users) {
req.session.users = {};
}
let token = req.get(TOKEN_KEY);
const { users } = req.session;
if (!token || !users[token]) {
token = Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, "");
const userInfo = getLoginInfo(req) || {};
users[token] = user;
}
return token;
};
const getSessionUser = (req) => {
const token = req.get(TOKEN_KEY);
if (token && req.session?.users) {
return req.session.users[token];
}
return null;
};
const genExpressSession = () => {
return session({
name: "demo.name",
secret: "demo.secret",
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 60 * 60 * 1e3,
expires: new Date(Date.now() + 60 * 60 * 1e3),
}, // 1 hour
store: new FileStore({
path: path.join(__dirname, "../sessions"),
retries: 0,
keyFunction: (secret, sessionId) => {
return secret + sessionId;
},
}),
});
};
module.exports = {
setSessionUser,
getSessionUser,
genExpressSession,
};
const path = require("path");
const Mock = require("mockjs");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const { isFunction } = require("lodash");
const argv = require("minimist")(process.argv.slice(2));
const isDev = (argv.env || "development") === "development";
const TOKEN_KEY = isDev ? "X-Auth-Token" : "X-Csrf-Token";
const setSessionUser = (req, getLoginInfo) => {
if (!isFunction(getLoginInfo)) {
throw new Error("getLoginInfo must be a function");
}
if (!req.session?.users) {
req.session.users = {};
}
let token = req.get(TOKEN_KEY);
const { users } = req.session;
if (!token || !users[token]) {
token = Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, "");
const userInfo = getLoginInfo(req) || {};
users[token] = user;
}
return token;
};
const getSessionUser = (req) => {
const token = req.get(TOKEN_KEY);
if (token && req.session?.users) {
return req.session.users[token];
}
return null;
};
const genExpressSession = () => {
return session({
name: "demo.name",
secret: "demo.secret",
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 60 * 60 * 1e3,
expires: new Date(Date.now() + 60 * 60 * 1e3),
}, // 1 hour
store: new FileStore({
path: path.join(__dirname, "../sessions"),
retries: 0,
keyFunction: (secret, sessionId) => {
return secret + sessionId;
},
}),
});
};
module.exports = {
setSessionUser,
getSessionUser,
genExpressSession,
};

View File

@@ -1,30 +1,30 @@
function log(message, type = "log", provided = 'console') {
const providedFn = globalThis[provided] || console;
if (providedFn && typeof providedFn[type] === 'function') {
const invokeMethod = providedFn[type ?? 'log'];
invokeMethod.call(providedFn, message);
}
}
function addMockPrefix(urlPrefix, api) {
const newMockApi = {};
Object.keys(api).map(apiKey=>{
newMockApi[apiKey] = urlPrefix + api[apiKey];
});
return new Proxy(newMockApi, {
get(target, prop) {
if (prop in target) {
return target[prop];
} else {
throw new Error(`API ${String(prop)} is not defined.`);
}
}
})
}
module.exports = {
log,
addMockPrefix,
function log(message, type = "log", provided = 'console') {
const providedFn = globalThis[provided] || console;
if (providedFn && typeof providedFn[type] === 'function') {
const invokeMethod = providedFn[type ?? 'log'];
invokeMethod.call(providedFn, message);
}
}
function addMockPrefix(urlPrefix, api) {
const newMockApi = {};
Object.keys(api).map(apiKey=>{
newMockApi[apiKey] = urlPrefix + api[apiKey];
});
return new Proxy(newMockApi, {
get(target, prop) {
if (prop in target) {
return target[prop];
} else {
throw new Error(`API ${String(prop)} is not defined.`);
}
}
})
}
module.exports = {
log,
addMockPrefix,
};

View File

@@ -1,13 +1,13 @@
const errorHandle = (err, req, res, next) => {
if(res.headersSent) {
return next(err);
}
console.error('Server Error:', err.message);
res.status(500).json({
code: '500',
msg: 'Internal Server Error',
data: null,
});
};
module.exports = errorHandle;
const errorHandle = (err, req, res, next) => {
if(res.headersSent) {
return next(err);
}
console.error('Server Error:', err.message);
res.status(500).json({
code: '500',
msg: 'Internal Server Error',
data: null,
});
};
module.exports = errorHandle;

View File

@@ -1,11 +1,11 @@
const setHeader = require('./set-header-middleware.cjs');
const strongMatch = require('./strong-match-middleware.cjs');
const sendJSON = require('./send-json-middleawre.cjs');
const errorHandle = require('./error-handle-middleware.cjs');
module.exports = {
setHeader,
strongMatch,
sendJSON,
errorHandle,
const setHeader = require('./set-header-middleware.cjs');
const strongMatch = require('./strong-match-middleware.cjs');
const sendJSON = require('./send-json-middleawre.cjs');
const errorHandle = require('./error-handle-middleware.cjs');
module.exports = {
setHeader,
strongMatch,
sendJSON,
errorHandle,
};

View File

@@ -1,18 +1,18 @@
const sendJSON = (req, res, next) => {
res.sendJSON = (
data = null,
{ code = '0', msg = 'success', statusCode = 200, timeout = 0 } = {}
) => {
const timer = setTimeout(() => {
res.status(statusCode).json({
code,
msg,
data,
});
clearTimeout(timer);
}, timeout);
};
next();
};
const sendJSON = (req, res, next) => {
res.sendJSON = (
data = null,
{ code = '0', msg = 'success', statusCode = 200, timeout = 0 } = {}
) => {
const timer = setTimeout(() => {
res.status(statusCode).json({
code,
msg,
data,
});
clearTimeout(timer);
}, timeout);
};
next();
};
module.exports = sendJSON;

View File

@@ -1,14 +1,14 @@
const setHeader = (req, res, next) => {
res.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src *; font-src 'self';",
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'SAMEORIGIN',
'X-XSS-Protection': '1; mode=block',
});
next();
};
const setHeader = (req, res, next) => {
res.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src *; font-src 'self';",
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'SAMEORIGIN',
'X-XSS-Protection': '1; mode=block',
});
next();
};
module.exports = setHeader;

View File

@@ -1,13 +1,13 @@
const API = require('../mock-apis.cjs');
const strongMatch = (req, res, next) => {
res.strongMatch = () => {
const { url } = req;
const index = url.indexOf('?');
const targetUrl = index !== -1 ? url.substring(0, index) : url;
const isExistedUrl = Object.values(API).includes(targetUrl);
return isExistedUrl;
};
next();
};
const API = require('../mock-apis.cjs');
const strongMatch = (req, res, next) => {
res.strongMatch = () => {
const { url } = req;
const index = url.indexOf('?');
const targetUrl = index !== -1 ? url.substring(0, index) : url;
const isExistedUrl = Object.values(API).includes(targetUrl);
return isExistedUrl;
};
next();
};
module.exports = strongMatch;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,232 +1,232 @@
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
const { Random } = Mock;
// 生成模拟数据归集统计信息
function dataXTemplate() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 15),
sourceType: Mock.Random.csentence(3, 10),
targetType: Mock.Random.csentence(3, 10),
description: Mock.Random.csentence(5, 20),
version: `v${Mock.Random.integer(1, 5)}.${Mock.Random.integer(
0,
9
)}.${Mock.Random.integer(0, 9)}`,
isSystem: Mock.Random.boolean(),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const templateList = new Array(20).fill(null).map(dataXTemplate);
// 生成模拟任务数据
function taskItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 20),
description: Mock.Random.csentence(5, 20),
syncMode: Mock.Random.pick(["ONCE", "SCHEDULED"]),
config: {
query: "SELECT * FROM table WHERE condition",
batchSize: Mock.Random.integer(100, 1000),
frequency: Mock.Random.integer(1, 60), // in minutes
},
scheduleExpression: "0 0 * * *", // cron expression
lastExecutionId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: Mock.Random.pick([
"DRAFT",
"READY",
"RUNNING",
"FAILED",
"STOPPED",
"SUCCESS",
]),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
sourceDataSourceId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
sourceDataSourceName: Mock.Random.ctitle(5, 20),
targetDataSourceId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
targetDataSourceName: Mock.Random.ctitle(5, 20),
};
}
const taskList = new Array(50).fill(null).map(taskItem);
// 生成模拟任务执行日志数据
function executionLogItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
taskName: Mock.Random.ctitle(5, 20),
dataSource: Mock.Random.ctitle(5, 15),
startTime: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
endTime: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
status: Mock.Random.pick(["SUCCESS", "FAILED", "RUNNING"]),
triggerType: Mock.Random.pick(["MANUAL", "SCHEDULED", "API"]),
duration: Mock.Random.integer(1, 120),
retryCount: Mock.Random.integer(0, 5),
recordsProcessed: Mock.Random.integer(100, 10000),
processId: Mock.Random.integer(1000, 9999),
errorMessage: Mock.Random.boolean() ? "" : Mock.Random.csentence(5, 20),
};
}
const executionLogList = new Array(100).fill(null).map(executionLogItem);
module.exports = function (router) {
// 获取任务列表
router.get(API.queryTasksUsingGet, (req, res) => {
const { keyword, status, page = 0, size = 10 } = req.query;
let filteredTasks = taskList;
if (keyword) {
filteredTasks = filteredTasks.filter((task) =>
task.name.includes(keyword)
);
}
if (status && status.length > 0) {
filteredTasks = filteredTasks.filter((task) =>
status.includes(task.status)
);
}
const startIndex = page * size;
const endIndex = startIndex + size;
const paginatedTasks = filteredTasks.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
totalElements: filteredTasks.length,
page,
size,
content: paginatedTasks,
},
});
});
router.get(API.queryDataXTemplatesUsingGet, (req, res) => {
const { keyword, page = 0, size = 10 } = req.query;
let filteredTemplates = templateList;
if (keyword) {
filteredTemplates = filteredTemplates.filter((template) =>
template.name.includes(keyword)
);
}
const startIndex = page * size;
const endIndex = startIndex + size;
const paginatedTemplates = filteredTemplates.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: paginatedTemplates,
totalElements: filteredTemplates.length,
page,
size,
},
});
});
// 创建任务
router.post(API.createTaskUsingPost, (req, res) => {
taskList.unshift(taskItem()); // 添加一个新的任务到列表开头
res.send({
code: "0",
msg: "任务创建成功",
data: {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
},
});
});
// 更新任务
router.post(API.updateTaskByIdUsingPut, (req, res) => {
const { id } = req.body;
res.send({
code: "0",
msg: "Data source task updated successfully",
data: taskList.find((task) => task.id === id),
});
});
// 删除任务
router.post(API.deleteTaskByIdUsingDelete, (req, res) => {
const { id } = req.body;
const index = taskList.findIndex((task) => task.id === id);
if (index !== -1) {
taskList.splice(index, 1);
}
res.send({
code: "0",
msg: "Data source task deleted successfully",
data: null,
});
});
// 执行任务
router.post(API.executeTaskByIdUsingPost, (req, res) => {
console.log("Received request to execute task", req.body);
const { id } = req.body;
console.log("Executing task with ID:", id);
taskList.find((task) => task.id === id).status = "RUNNING";
res.send({
code: "0",
msg: "Data source task execution started",
data: null,
});
});
// 停止任务
router.post(API.stopTaskByIdUsingPost, (req, res) => {
const { id } = req.body;
const task = taskList.find((task) => task.id === id);
if (task) {
task.status = "STOPPED";
}
res.send({
code: "0",
msg: "Data source task stopped successfully",
data: null,
});
});
// 获取任务执行日志
router.post(API.queryExecutionLogUsingPost, (req, res) => {
const { keyword, page = 1, size = 10, status } = req.body;
let filteredLogs = executionLogList;
if (keyword) {
filteredLogs = filteredLogs.filter((log) =>
log.taskName.includes(keyword)
);
}
if (status && status.length > 0) {
filteredLogs = filteredLogs.filter((log) => status.includes(log.status));
}
const startIndex = (page - 1) * size;
const endIndex = startIndex + size;
const paginatedLogs = filteredLogs.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
totalElements: filteredLogs.length,
page,
size,
results: paginatedLogs,
},
});
});
// 获取任务执行日志详情
router.post(API.queryExecutionLogByIdUsingGet, (req, res) => {
const { id } = req.body;
const log = executionLogList.find((log) => log.id === id);
res.send({
code: "0",
msg: "Success",
data: log,
});
});
};
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
const { Random } = Mock;
// 生成模拟数据归集统计信息
function dataXTemplate() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 15),
sourceType: Mock.Random.csentence(3, 10),
targetType: Mock.Random.csentence(3, 10),
description: Mock.Random.csentence(5, 20),
version: `v${Mock.Random.integer(1, 5)}.${Mock.Random.integer(
0,
9
)}.${Mock.Random.integer(0, 9)}`,
isSystem: Mock.Random.boolean(),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const templateList = new Array(20).fill(null).map(dataXTemplate);
// 生成模拟任务数据
function taskItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 20),
description: Mock.Random.csentence(5, 20),
syncMode: Mock.Random.pick(["ONCE", "SCHEDULED"]),
config: {
query: "SELECT * FROM table WHERE condition",
batchSize: Mock.Random.integer(100, 1000),
frequency: Mock.Random.integer(1, 60), // in minutes
},
scheduleExpression: "0 0 * * *", // cron expression
lastExecutionId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: Mock.Random.pick([
"DRAFT",
"READY",
"RUNNING",
"FAILED",
"STOPPED",
"SUCCESS",
]),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
sourceDataSourceId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
sourceDataSourceName: Mock.Random.ctitle(5, 20),
targetDataSourceId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
targetDataSourceName: Mock.Random.ctitle(5, 20),
};
}
const taskList = new Array(50).fill(null).map(taskItem);
// 生成模拟任务执行日志数据
function executionLogItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
taskName: Mock.Random.ctitle(5, 20),
dataSource: Mock.Random.ctitle(5, 15),
startTime: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
endTime: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
status: Mock.Random.pick(["SUCCESS", "FAILED", "RUNNING"]),
triggerType: Mock.Random.pick(["MANUAL", "SCHEDULED", "API"]),
duration: Mock.Random.integer(1, 120),
retryCount: Mock.Random.integer(0, 5),
recordsProcessed: Mock.Random.integer(100, 10000),
processId: Mock.Random.integer(1000, 9999),
errorMessage: Mock.Random.boolean() ? "" : Mock.Random.csentence(5, 20),
};
}
const executionLogList = new Array(100).fill(null).map(executionLogItem);
module.exports = function (router) {
// 获取任务列表
router.get(API.queryTasksUsingGet, (req, res) => {
const { keyword, status, page = 0, size = 10 } = req.query;
let filteredTasks = taskList;
if (keyword) {
filteredTasks = filteredTasks.filter((task) =>
task.name.includes(keyword)
);
}
if (status && status.length > 0) {
filteredTasks = filteredTasks.filter((task) =>
status.includes(task.status)
);
}
const startIndex = page * size;
const endIndex = startIndex + size;
const paginatedTasks = filteredTasks.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
totalElements: filteredTasks.length,
page,
size,
content: paginatedTasks,
},
});
});
router.get(API.queryDataXTemplatesUsingGet, (req, res) => {
const { keyword, page = 0, size = 10 } = req.query;
let filteredTemplates = templateList;
if (keyword) {
filteredTemplates = filteredTemplates.filter((template) =>
template.name.includes(keyword)
);
}
const startIndex = page * size;
const endIndex = startIndex + size;
const paginatedTemplates = filteredTemplates.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: paginatedTemplates,
totalElements: filteredTemplates.length,
page,
size,
},
});
});
// 创建任务
router.post(API.createTaskUsingPost, (req, res) => {
taskList.unshift(taskItem()); // 添加一个新的任务到列表开头
res.send({
code: "0",
msg: "任务创建成功",
data: {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
},
});
});
// 更新任务
router.post(API.updateTaskByIdUsingPut, (req, res) => {
const { id } = req.body;
res.send({
code: "0",
msg: "Data source task updated successfully",
data: taskList.find((task) => task.id === id),
});
});
// 删除任务
router.post(API.deleteTaskByIdUsingDelete, (req, res) => {
const { id } = req.body;
const index = taskList.findIndex((task) => task.id === id);
if (index !== -1) {
taskList.splice(index, 1);
}
res.send({
code: "0",
msg: "Data source task deleted successfully",
data: null,
});
});
// 执行任务
router.post(API.executeTaskByIdUsingPost, (req, res) => {
console.log("Received request to execute task", req.body);
const { id } = req.body;
console.log("Executing task with ID:", id);
taskList.find((task) => task.id === id).status = "RUNNING";
res.send({
code: "0",
msg: "Data source task execution started",
data: null,
});
});
// 停止任务
router.post(API.stopTaskByIdUsingPost, (req, res) => {
const { id } = req.body;
const task = taskList.find((task) => task.id === id);
if (task) {
task.status = "STOPPED";
}
res.send({
code: "0",
msg: "Data source task stopped successfully",
data: null,
});
});
// 获取任务执行日志
router.post(API.queryExecutionLogUsingPost, (req, res) => {
const { keyword, page = 1, size = 10, status } = req.body;
let filteredLogs = executionLogList;
if (keyword) {
filteredLogs = filteredLogs.filter((log) =>
log.taskName.includes(keyword)
);
}
if (status && status.length > 0) {
filteredLogs = filteredLogs.filter((log) => status.includes(log.status));
}
const startIndex = (page - 1) * size;
const endIndex = startIndex + size;
const paginatedLogs = filteredLogs.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
totalElements: filteredLogs.length,
page,
size,
results: paginatedLogs,
},
});
});
// 获取任务执行日志详情
router.post(API.queryExecutionLogByIdUsingGet, (req, res) => {
const { id } = req.body;
const log = executionLogList.find((log) => log.id === id);
res.send({
code: "0",
msg: "Success",
data: log,
});
});
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,435 +1,435 @@
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
function tagItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.word(3, 10),
description: Mock.Random.csentence(5, 20),
color: Mock.Random.color(),
usageCount: Mock.Random.integer(0, 100),
};
}
const tagList = new Array(20).fill(null).map((_, index) => tagItem(index));
function datasetItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 20),
datasetType: Mock.Random.pick(["TEXT", "IMAGE", "AUDIO", "VIDEO"]),
status: Mock.Random.pick(["DRAFT","ACTIVE", "INACTIVE", "PROCESSING"]),
tags: Mock.Random.shuffle(tagList).slice(0, Mock.Random.integer(1, 3)),
totalSize: Mock.Random.integer(1024, 1024 * 1024 * 1024), // in bytes
description: Mock.Random.cparagraph(1, 3),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
createdBy: Mock.Random.cname(),
updatedBy: Mock.Random.cname(),
};
}
const datasetList = new Array(50)
.fill(null)
.map((_, index) => datasetItem(index));
function datasetFileItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
fileName:
Mock.Random.word(5, 15) +
"." +
Mock.Random.pick(["csv", "json", "xml", "parquet", "avro"]),
originName:
Mock.Random.word(5, 15) +
"." +
Mock.Random.pick(["csv", "json", "xml", "parquet", "avro"]),
fileType: Mock.Random.pick(["CSV", "JSON", "XML", "Parquet", "Avro"]),
size: Mock.Random.integer(1024, 1024 * 1024 * 1024), // in bytes
type: Mock.Random.pick(["CSV", "JSON", "XML", "Parquet", "Avro"]),
status: Mock.Random.pick(["UPLOADED", "PROCESSING", "COMPLETED", "ERROR"]),
description: Mock.Random.csentence(5, 20),
filePath: "/path/to/file/" + Mock.Random.word(5, 10),
uploadedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
uploadedBy: Mock.Random.cname(),
};
}
const datasetFileList = new Array(200)
.fill(null)
.map((_, index) => datasetFileItem(index));
const datasetStatistics = {
count: {
text: 10,
image: 34,
audio: 23,
video: 5,
},
size: {
text: "120 MB",
image: "3.4 GB",
audio: "2.3 GB",
video: "15 GB",
},
totalDatasets: datasetList.length,
totalFiles: datasetFileList.length,
completedFiles: datasetFileList.filter((file) => file.status === "COMPLETED")
.length,
totalSize: datasetFileList.reduce((acc, file) => acc + file.size, 0), // in bytes
completionRate:
datasetFileList.length === 0
? 0
: Math.round(
(datasetFileList.filter((file) => file.status === "COMPLETED")
.length /
datasetFileList.length) *
100
), // percentage
};
const datasetTypes = [
{
code: "PRETRAIN",
name: "预训练数据集",
description: "用于模型预训练的大规模数据集",
supportedFormats: ["txt", "json", "csv", "parquet"],
icon: "brain",
},
{
code: "FINE_TUNE",
name: "微调数据集",
description: "用于模型微调的专业数据集",
supportedFormats: ["json", "csv", "xlsx"],
icon: "tune",
},
{
code: "EVAL",
name: "评估数据集",
description: "用于模型评估的标准数据集",
supportedFormats: ["json", "csv", "xml"],
icon: "assessment",
},
];
module.exports = { datasetList };
module.exports = function (router) {
// 获取数据统计信息
router.get(API.queryDatasetStatisticsUsingGet, (req, res) => {
res.send({
code: "0",
msg: "Success",
data: datasetStatistics,
});
});
// 创建数据
router.post(API.createDatasetUsingPost, (req, res) => {
const newDataset = {
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: "ACTIVE",
fileCount: 0,
totalSize: 0,
completionRate: 0,
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
createdBy: "Admin",
updatedBy: "Admin",
tags: tagList.filter((tag) => req.body?.tagIds?.includes?.(tag.id)),
};
datasetList.unshift(newDataset); // Add to the beginning of the list
res.send({
code: "0",
msg: "Dataset created successfully",
data: newDataset,
});
});
// 获取数据集列表
router.get(API.queryDatasetsUsingGet, (req, res) => {
const { page = 0, size = 10, keyword, type, status, tags } = req.query;
console.log("Received query params:", req.query);
let filteredDatasets = datasetList;
if (keyword) {
console.log("filter keyword:", keyword);
filteredDatasets = filteredDatasets.filter(
(dataset) =>
dataset.name.includes(keyword) ||
dataset.description.includes(keyword)
);
}
if (type) {
filteredDatasets = filteredDatasets.filter(
(dataset) => dataset.datasetType === type
);
}
if (status) {
console.log("filter status:", status);
filteredDatasets = filteredDatasets.filter(
(dataset) => dataset.status === status
);
}
if (tags && tags.length > 0) {
console.log("filter tags:", tags);
filteredDatasets = filteredDatasets.filter((dataset) =>
tags.every((tag) => dataset.tags.some((t) => t.name === tag))
);
}
const totalElements = filteredDatasets.length;
const paginatedDatasets = filteredDatasets.slice(
page * size,
(page + 1) * size
);
res.send({
code: "0",
msg: "Success",
data: {
totalElements,
page,
size,
content: paginatedDatasets,
},
});
});
// 根据ID获取数据集详情
router.get(API.queryDatasetByIdUsingGet, (req, res) => {
const { id } = req.params;
const dataset = datasetList.find((d) => d.id === id);
if (dataset) {
res.send({
code: "0",
msg: "Success",
data: dataset,
});
} else {
res.status(404).send({
code: "1",
msg: "Dataset not found",
data: null,
});
}
});
// 更新数据集
router.put(API.updateDatasetByIdUsingPut, (req, res) => {
const { id } = req.params;
let { tags } = req.body;
const index = datasetList.findIndex((d) => d.id === id);
tags = [...datasetList[index].tags.map((tag) => tag.name), ...tags];
if (index !== -1) {
datasetList[index] = {
...datasetList[index],
...req.body,
tags: tagList.filter((tag) => tags?.includes?.(tag.name)),
updatedAt: new Date().toISOString(),
updatedBy: "Admin",
};
res.send({
code: "0",
msg: "Dataset updated successfully",
data: datasetList[index],
});
} else {
res.status(404).send({
code: "1",
msg: "Dataset not found",
data: null,
});
}
});
// 删除数据集
router.delete(API.deleteDatasetByIdUsingDelete, (req, res) => {
const { datasetId } = req.params;
const index = datasetList.findIndex((d) => d.id === datasetId);
if (index !== -1) {
datasetList.splice(index, 1);
res.status(204).send();
} else {
res.status(404).send({
code: "1",
msg: "Dataset not found",
data: null,
});
}
});
// 获取数据集文件列表
router.get(API.queryFilesUsingGet, (req, res) => {
const { datasetId } = req.params;
const { page = 0, size = 20, fileType, status } = req.query;
let filteredFiles = datasetFileList;
if (fileType) {
filteredFiles = filteredFiles.filter(
(file) => file.fileType === fileType
);
}
if (status) {
filteredFiles = filteredFiles.filter((file) => file.status === status);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredFiles.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: pageData,
page: parseInt(page),
size: parseInt(size),
totalElements: filteredFiles.length,
},
});
});
// 上传文件到数据集
router.post(API.uploadFileUsingPost, (req, res) => {
const { datasetId } = req.params;
const newFile = {
...datasetFileItem(),
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
uploadedAt: new Date().toISOString(),
uploadedBy: "Admin",
};
datasetFileList.push(newFile);
res.status(201).send({
code: "0",
msg: "File uploaded successfully",
data: newFile,
});
});
// 获取文件详情
router.get(API.queryFileByIdUsingGet, (req, res) => {
const { datasetId, fileId } = req.params;
const file = datasetFileList.find((f) => f.id === fileId);
if (file) {
res.send({
code: "0",
msg: "Success",
data: file,
});
} else {
res.status(404).send({
code: "1",
msg: "File not found",
data: null,
});
}
});
// 删除文件
router.delete(API.deleteFileByIdUsingDelete, (req, res) => {
const { datasetId, fileId } = req.params;
const index = datasetFileList.findIndex((f) => f.id === fileId);
if (index !== -1) {
datasetFileList.splice(index, 1);
res.status(204).send();
} else {
res.status(404).send({
code: "1",
msg: "File not found",
data: null,
});
}
});
// 下载文件
router.get(API.downloadFileByIdUsingGet, (req, res) => {
const { datasetId, fileId } = req.params;
const file = datasetFileList.find((f) => f.id === fileId);
if (file) {
res.setHeader(
"Content-Disposition",
`attachment; filename="${file.fileName}"`
);
res.setHeader("Content-Type", "application/octet-stream");
res.send(`Mock file content for ${file.fileName}`);
} else {
res.status(404).send({
code: "1",
msg: "File not found",
data: null,
});
}
});
// 获取数据集类型列表
router.get(API.queryDatasetTypesUsingGet, (req, res) => {
res.send({
code: "0",
msg: "Success",
data: datasetTypes,
});
});
// 获取标签列表
router.get(API.queryTagsUsingGet, (req, res) => {
const { keyword } = req.query;
let filteredTags = tagList;
if (keyword) {
filteredTags = tagList.filter((tag) =>
tag.name.toLowerCase().includes(keyword.toLowerCase())
);
}
res.send({
code: "0",
msg: "Success",
data: filteredTags,
});
});
// 创建标签
router.post(API.createTagUsingPost, (req, res) => {
const newTag = {
...tagItem(),
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
usageCount: 0,
};
tagList.push(newTag);
res.status(201).send({
code: "0",
msg: "Tag created successfully",
data: newTag,
});
});
router.post(API.preUploadFileUsingPost, (req, res) => {
res.status(201).send(Mock.Random.guid());
});
// 上传
router.post(API.uploadFileChunkUsingPost, (req, res) => {
res.status(500).send({ message: "Simulated upload failure" });
// res.status(201).send({ data: "success" });
});
// 取消上传
router.put(API.cancelUploadUsingPut, (req, res) => {
res.status(201).send({ data: "success" });
});
};
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
function tagItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.word(3, 10),
description: Mock.Random.csentence(5, 20),
color: Mock.Random.color(),
usageCount: Mock.Random.integer(0, 100),
};
}
const tagList = new Array(20).fill(null).map((_, index) => tagItem(index));
function datasetItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 20),
datasetType: Mock.Random.pick(["TEXT", "IMAGE", "AUDIO", "VIDEO"]),
status: Mock.Random.pick(["DRAFT","ACTIVE", "INACTIVE", "PROCESSING"]),
tags: Mock.Random.shuffle(tagList).slice(0, Mock.Random.integer(1, 3)),
totalSize: Mock.Random.integer(1024, 1024 * 1024 * 1024), // in bytes
description: Mock.Random.cparagraph(1, 3),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
createdBy: Mock.Random.cname(),
updatedBy: Mock.Random.cname(),
};
}
const datasetList = new Array(50)
.fill(null)
.map((_, index) => datasetItem(index));
function datasetFileItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
fileName:
Mock.Random.word(5, 15) +
"." +
Mock.Random.pick(["csv", "json", "xml", "parquet", "avro"]),
originName:
Mock.Random.word(5, 15) +
"." +
Mock.Random.pick(["csv", "json", "xml", "parquet", "avro"]),
fileType: Mock.Random.pick(["CSV", "JSON", "XML", "Parquet", "Avro"]),
size: Mock.Random.integer(1024, 1024 * 1024 * 1024), // in bytes
type: Mock.Random.pick(["CSV", "JSON", "XML", "Parquet", "Avro"]),
status: Mock.Random.pick(["UPLOADED", "PROCESSING", "COMPLETED", "ERROR"]),
description: Mock.Random.csentence(5, 20),
filePath: "/path/to/file/" + Mock.Random.word(5, 10),
uploadedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
uploadedBy: Mock.Random.cname(),
};
}
const datasetFileList = new Array(200)
.fill(null)
.map((_, index) => datasetFileItem(index));
const datasetStatistics = {
count: {
text: 10,
image: 34,
audio: 23,
video: 5,
},
size: {
text: "120 MB",
image: "3.4 GB",
audio: "2.3 GB",
video: "15 GB",
},
totalDatasets: datasetList.length,
totalFiles: datasetFileList.length,
completedFiles: datasetFileList.filter((file) => file.status === "COMPLETED")
.length,
totalSize: datasetFileList.reduce((acc, file) => acc + file.size, 0), // in bytes
completionRate:
datasetFileList.length === 0
? 0
: Math.round(
(datasetFileList.filter((file) => file.status === "COMPLETED")
.length /
datasetFileList.length) *
100
), // percentage
};
const datasetTypes = [
{
code: "PRETRAIN",
name: "预训练数据集",
description: "用于模型预训练的大规模数据集",
supportedFormats: ["txt", "json", "csv", "parquet"],
icon: "brain",
},
{
code: "FINE_TUNE",
name: "微调数据集",
description: "用于模型微调的专业数据集",
supportedFormats: ["json", "csv", "xlsx"],
icon: "tune",
},
{
code: "EVAL",
name: "评估数据集",
description: "用于模型评估的标准数据集",
supportedFormats: ["json", "csv", "xml"],
icon: "assessment",
},
];
module.exports = { datasetList };
module.exports = function (router) {
// 获取数据统计信息
router.get(API.queryDatasetStatisticsUsingGet, (req, res) => {
res.send({
code: "0",
msg: "Success",
data: datasetStatistics,
});
});
// 创建数据
router.post(API.createDatasetUsingPost, (req, res) => {
const newDataset = {
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: "ACTIVE",
fileCount: 0,
totalSize: 0,
completionRate: 0,
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
createdBy: "Admin",
updatedBy: "Admin",
tags: tagList.filter((tag) => req.body?.tagIds?.includes?.(tag.id)),
};
datasetList.unshift(newDataset); // Add to the beginning of the list
res.send({
code: "0",
msg: "Dataset created successfully",
data: newDataset,
});
});
// 获取数据集列表
router.get(API.queryDatasetsUsingGet, (req, res) => {
const { page = 0, size = 10, keyword, type, status, tags } = req.query;
console.log("Received query params:", req.query);
let filteredDatasets = datasetList;
if (keyword) {
console.log("filter keyword:", keyword);
filteredDatasets = filteredDatasets.filter(
(dataset) =>
dataset.name.includes(keyword) ||
dataset.description.includes(keyword)
);
}
if (type) {
filteredDatasets = filteredDatasets.filter(
(dataset) => dataset.datasetType === type
);
}
if (status) {
console.log("filter status:", status);
filteredDatasets = filteredDatasets.filter(
(dataset) => dataset.status === status
);
}
if (tags && tags.length > 0) {
console.log("filter tags:", tags);
filteredDatasets = filteredDatasets.filter((dataset) =>
tags.every((tag) => dataset.tags.some((t) => t.name === tag))
);
}
const totalElements = filteredDatasets.length;
const paginatedDatasets = filteredDatasets.slice(
page * size,
(page + 1) * size
);
res.send({
code: "0",
msg: "Success",
data: {
totalElements,
page,
size,
content: paginatedDatasets,
},
});
});
// 根据ID获取数据集详情
router.get(API.queryDatasetByIdUsingGet, (req, res) => {
const { id } = req.params;
const dataset = datasetList.find((d) => d.id === id);
if (dataset) {
res.send({
code: "0",
msg: "Success",
data: dataset,
});
} else {
res.status(404).send({
code: "1",
msg: "Dataset not found",
data: null,
});
}
});
// 更新数据集
router.put(API.updateDatasetByIdUsingPut, (req, res) => {
const { id } = req.params;
let { tags } = req.body;
const index = datasetList.findIndex((d) => d.id === id);
tags = [...datasetList[index].tags.map((tag) => tag.name), ...tags];
if (index !== -1) {
datasetList[index] = {
...datasetList[index],
...req.body,
tags: tagList.filter((tag) => tags?.includes?.(tag.name)),
updatedAt: new Date().toISOString(),
updatedBy: "Admin",
};
res.send({
code: "0",
msg: "Dataset updated successfully",
data: datasetList[index],
});
} else {
res.status(404).send({
code: "1",
msg: "Dataset not found",
data: null,
});
}
});
// 删除数据集
router.delete(API.deleteDatasetByIdUsingDelete, (req, res) => {
const { datasetId } = req.params;
const index = datasetList.findIndex((d) => d.id === datasetId);
if (index !== -1) {
datasetList.splice(index, 1);
res.status(204).send();
} else {
res.status(404).send({
code: "1",
msg: "Dataset not found",
data: null,
});
}
});
// 获取数据集文件列表
router.get(API.queryFilesUsingGet, (req, res) => {
const { datasetId } = req.params;
const { page = 0, size = 20, fileType, status } = req.query;
let filteredFiles = datasetFileList;
if (fileType) {
filteredFiles = filteredFiles.filter(
(file) => file.fileType === fileType
);
}
if (status) {
filteredFiles = filteredFiles.filter((file) => file.status === status);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredFiles.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: pageData,
page: parseInt(page),
size: parseInt(size),
totalElements: filteredFiles.length,
},
});
});
// 上传文件到数据集
router.post(API.uploadFileUsingPost, (req, res) => {
const { datasetId } = req.params;
const newFile = {
...datasetFileItem(),
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
uploadedAt: new Date().toISOString(),
uploadedBy: "Admin",
};
datasetFileList.push(newFile);
res.status(201).send({
code: "0",
msg: "File uploaded successfully",
data: newFile,
});
});
// 获取文件详情
router.get(API.queryFileByIdUsingGet, (req, res) => {
const { datasetId, fileId } = req.params;
const file = datasetFileList.find((f) => f.id === fileId);
if (file) {
res.send({
code: "0",
msg: "Success",
data: file,
});
} else {
res.status(404).send({
code: "1",
msg: "File not found",
data: null,
});
}
});
// 删除文件
router.delete(API.deleteFileByIdUsingDelete, (req, res) => {
const { datasetId, fileId } = req.params;
const index = datasetFileList.findIndex((f) => f.id === fileId);
if (index !== -1) {
datasetFileList.splice(index, 1);
res.status(204).send();
} else {
res.status(404).send({
code: "1",
msg: "File not found",
data: null,
});
}
});
// 下载文件
router.get(API.downloadFileByIdUsingGet, (req, res) => {
const { datasetId, fileId } = req.params;
const file = datasetFileList.find((f) => f.id === fileId);
if (file) {
res.setHeader(
"Content-Disposition",
`attachment; filename="${file.fileName}"`
);
res.setHeader("Content-Type", "application/octet-stream");
res.send(`Mock file content for ${file.fileName}`);
} else {
res.status(404).send({
code: "1",
msg: "File not found",
data: null,
});
}
});
// 获取数据集类型列表
router.get(API.queryDatasetTypesUsingGet, (req, res) => {
res.send({
code: "0",
msg: "Success",
data: datasetTypes,
});
});
// 获取标签列表
router.get(API.queryTagsUsingGet, (req, res) => {
const { keyword } = req.query;
let filteredTags = tagList;
if (keyword) {
filteredTags = tagList.filter((tag) =>
tag.name.toLowerCase().includes(keyword.toLowerCase())
);
}
res.send({
code: "0",
msg: "Success",
data: filteredTags,
});
});
// 创建标签
router.post(API.createTagUsingPost, (req, res) => {
const newTag = {
...tagItem(),
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
usageCount: 0,
};
tagList.push(newTag);
res.status(201).send({
code: "0",
msg: "Tag created successfully",
data: newTag,
});
});
router.post(API.preUploadFileUsingPost, (req, res) => {
res.status(201).send(Mock.Random.guid());
});
// 上传
router.post(API.uploadFileChunkUsingPost, (req, res) => {
res.status(500).send({ message: "Simulated upload failure" });
// res.status(201).send({ data: "success" });
});
// 取消上传
router.put(API.cancelUploadUsingPut, (req, res) => {
res.status(201).send({ data: "success" });
});
};

View File

@@ -1,220 +1,220 @@
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
function ratioJobItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 15),
description: Mock.Random.csentence(10, 30),
status: Mock.Random.pick(["PENDING", "RUNNING", "COMPLETED", "FAILED", "PAUSED"]),
totals: Mock.Random.integer(1000, 10000),
ratio_method: Mock.Random.pick(["DATASET", "TAG"]),
target_dataset_id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
target_dataset_name: Mock.Random.ctitle(3, 8),
config: [
{
datasetId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
counts: Mock.Random.integer(100, 1000).toString(),
filter_conditions: "",
},
{
datasetId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
counts: Mock.Random.integer(100, 1000).toString(),
filter_conditions: "",
},
],
created_at: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updated_at: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const ratioJobList = new Array(20).fill(null).map(ratioJobItem);
module.exports = function (router) {
// 获取配比任务列表
router.get(API.queryRatioTasksUsingGet, (req, res) => {
const { page = 0, size = 10, status } = req.query;
let filteredJobs = ratioJobList;
if (status) {
filteredJobs = ratioJobList.filter((job) => job.status === status);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredJobs.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: pageData,
totalElements: filteredJobs.length,
totalPages: Math.ceil(filteredJobs.length / size),
size: parseInt(size),
number: parseInt(page),
},
});
});
// 创建配比任务
router.post(API.createRatioTaskUsingPost, (req, res) => {
const newJob = {
...ratioJobItem(),
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: "PENDING",
createdAt: new Date().toISOString(),
};
ratioJobList.push(newJob);
res.status(201).send({
code: "0",
msg: "Ratio job created successfully",
data: newJob,
});
});
// 获取配比任务详情
router.get(API.queryRatioTaskByIdUsingGet, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
res.send({
code: "0",
msg: "Success",
data: job,
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 删除配比任务
router.delete(API.deleteRatioTaskByIdUsingDelete, (req, res) => {
const { taskId } = req.params;
const index = ratioJobList.findIndex((j) => j.id === taskId);
if (index !== -1) {
ratioJobList.splice(index, 1);
res.send({
code: "0",
msg: "Ratio job deleted successfully",
data: null,
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 更新配比任务
router.put(API.updateRatioTaskByIdUsingPut, (req, res) => {
const { taskId } = req.params;
const index = ratioJobList.findIndex((j) => j.id === taskId);
if (index !== -1) {
ratioJobList[index] = {
...ratioJobList[index],
...req.body,
updatedAt: new Date().toISOString(),
};
res.send({
code: "0",
msg: "Ratio job updated successfully",
data: ratioJobList[index],
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 执行配比任务
router.post(API.executeRatioTaskByIdUsingPost, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
job.status = "RUNNING";
job.startedAt = new Date().toISOString();
res.send({
code: "0",
msg: "Ratio job execution started",
data: {
executionId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: "RUNNING",
message: "Job execution started successfully",
},
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 停止配比任务
router.post(API.stopRatioTaskByIdUsingPost, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
job.status = "STOPPED";
job.finishedAt = new Date().toISOString();
res.send({
code: "0",
msg: "Ratio job stopped successfully",
data: null,
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 获取配比任务状态
router.get(API.queryRatioJobStatusUsingGet, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
res.send({
code: "0",
msg: "Success",
data: {
status: job.status,
progress: job.progress,
},
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 获取配比模型列表
router.get(API.queryRatioModelsUsingGet, (req, res) => {
const models = [
{ id: "model1", name: "均匀分配模型", description: "将目标数量均匀分配到各数据集。" },
{ id: "model2", name: "标签优先模型", description: "优先满足标签配比需求。" },
{ id: "model3", name: "自定义模型", description: "支持自定义分配逻辑。" },
];
res.send({
code: "0",
msg: "Success",
data: models,
});
});
};
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
function ratioJobItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 15),
description: Mock.Random.csentence(10, 30),
status: Mock.Random.pick(["PENDING", "RUNNING", "COMPLETED", "FAILED", "PAUSED"]),
totals: Mock.Random.integer(1000, 10000),
ratio_method: Mock.Random.pick(["DATASET", "TAG"]),
target_dataset_id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
target_dataset_name: Mock.Random.ctitle(3, 8),
config: [
{
datasetId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
counts: Mock.Random.integer(100, 1000).toString(),
filter_conditions: "",
},
{
datasetId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
counts: Mock.Random.integer(100, 1000).toString(),
filter_conditions: "",
},
],
created_at: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updated_at: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const ratioJobList = new Array(20).fill(null).map(ratioJobItem);
module.exports = function (router) {
// 获取配比任务列表
router.get(API.queryRatioTasksUsingGet, (req, res) => {
const { page = 0, size = 10, status } = req.query;
let filteredJobs = ratioJobList;
if (status) {
filteredJobs = ratioJobList.filter((job) => job.status === status);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredJobs.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: pageData,
totalElements: filteredJobs.length,
totalPages: Math.ceil(filteredJobs.length / size),
size: parseInt(size),
number: parseInt(page),
},
});
});
// 创建配比任务
router.post(API.createRatioTaskUsingPost, (req, res) => {
const newJob = {
...ratioJobItem(),
...req.body,
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: "PENDING",
createdAt: new Date().toISOString(),
};
ratioJobList.push(newJob);
res.status(201).send({
code: "0",
msg: "Ratio job created successfully",
data: newJob,
});
});
// 获取配比任务详情
router.get(API.queryRatioTaskByIdUsingGet, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
res.send({
code: "0",
msg: "Success",
data: job,
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 删除配比任务
router.delete(API.deleteRatioTaskByIdUsingDelete, (req, res) => {
const { taskId } = req.params;
const index = ratioJobList.findIndex((j) => j.id === taskId);
if (index !== -1) {
ratioJobList.splice(index, 1);
res.send({
code: "0",
msg: "Ratio job deleted successfully",
data: null,
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 更新配比任务
router.put(API.updateRatioTaskByIdUsingPut, (req, res) => {
const { taskId } = req.params;
const index = ratioJobList.findIndex((j) => j.id === taskId);
if (index !== -1) {
ratioJobList[index] = {
...ratioJobList[index],
...req.body,
updatedAt: new Date().toISOString(),
};
res.send({
code: "0",
msg: "Ratio job updated successfully",
data: ratioJobList[index],
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 执行配比任务
router.post(API.executeRatioTaskByIdUsingPost, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
job.status = "RUNNING";
job.startedAt = new Date().toISOString();
res.send({
code: "0",
msg: "Ratio job execution started",
data: {
executionId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
status: "RUNNING",
message: "Job execution started successfully",
},
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 停止配比任务
router.post(API.stopRatioTaskByIdUsingPost, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
job.status = "STOPPED";
job.finishedAt = new Date().toISOString();
res.send({
code: "0",
msg: "Ratio job stopped successfully",
data: null,
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 获取配比任务状态
router.get(API.queryRatioJobStatusUsingGet, (req, res) => {
const { taskId } = req.params;
const job = ratioJobList.find((j) => j.id === taskId);
if (job) {
res.send({
code: "0",
msg: "Success",
data: {
status: job.status,
progress: job.progress,
},
});
} else {
res.status(404).send({
code: "1",
msg: "Ratio job not found",
data: null,
});
}
});
// 获取配比模型列表
router.get(API.queryRatioModelsUsingGet, (req, res) => {
const models = [
{ id: "model1", name: "均匀分配模型", description: "将目标数量均匀分配到各数据集。" },
{ id: "model2", name: "标签优先模型", description: "优先满足标签配比需求。" },
{ id: "model3", name: "自定义模型", description: "支持自定义分配逻辑。" },
];
res.send({
code: "0",
msg: "Success",
data: models,
});
});
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,176 +1,176 @@
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
// 知识库数据
function KnowledgeBaseItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 15),
description: Mock.Random.csentence(10, 30),
createdBy: Mock.Random.cname(),
updatedBy: Mock.Random.cname(),
embeddingModel: Mock.Random.pick([
"text-embedding-ada-002",
"text-embedding-3-small",
"text-embedding-3-large",
]),
chatModel: Mock.Random.pick(["gpt-3.5-turbo", "gpt-4", "gpt-4-32k"]),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const knowledgeBaseList = new Array(50).fill(null).map(KnowledgeBaseItem);
function fileItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
createdBy: Mock.Random.cname(),
updatedBy: Mock.Random.cname(),
knowledgeBaseId: Mock.Random.pick(knowledgeBaseList).id,
fileId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
fileName: Mock.Random.ctitle(5, 15),
chunkCount: Mock.Random.integer(1, 100),
metadata: {},
status: Mock.Random.pick([
"UNPROCESSED",
"PROCESSING",
"PROCESSED",
"PROCESS_FAILED",
]),
};
}
const fileList = new Array(20).fill(null).map(fileItem);
module.exports = function (router) {
// 获取知识库列表
router.post(API.queryKnowledgeBasesUsingPost, (req, res) => {
const { page = 0, size, keyword } = req.body;
let filteredList = knowledgeBaseList;
if (keyword) {
filteredList = knowledgeBaseList.filter(
(kb) => kb.name.includes(keyword) || kb.description.includes(keyword)
);
}
const start = page * size;
const end = start + size;
const totalElements = filteredList.length;
const paginatedList = filteredList.slice(start, end);
res.send({
code: "0",
msg: "Success",
data: {
totalElements,
page,
size,
content: paginatedList,
},
});
});
// 创建知识库
router.post(API.createKnowledgeBaseUsingPost, (req, res) => {
const item = KnowledgeBaseItem();
knowledgeBaseList.unshift(item);
res.status(201).send(item);
});
// 获取知识库详情
router.get(API.queryKnowledgeBaseByIdUsingGet, (req, res) => {
const id = req.params.baseId;
const item =
knowledgeBaseList.find((kb) => kb.id === id) || KnowledgeBaseItem();
res.send({
code: "0",
msg: "Success",
data: item,
});
});
// 更新知识库
router.put(API.updateKnowledgeBaseByIdUsingPut, (req, res) => {
const id = req.params.baseId;
const idx = knowledgeBaseList.findIndex((kb) => kb.id === id);
if (idx >= 0) {
knowledgeBaseList[idx] = { ...knowledgeBaseList[idx], ...req.body };
res.status(201).send(knowledgeBaseList[idx]);
} else {
res.status(404).send({ message: "Not found" });
}
});
// 删除知识库
router.delete(API.deleteKnowledgeBaseByIdUsingDelete, (req, res) => {
const id = req.params.baseId;
const idx = knowledgeBaseList.findIndex((kb) => kb.id === id);
if (idx >= 0) {
knowledgeBaseList.splice(idx, 1);
res.status(201).send({ success: true });
} else {
res.status(404).send({ message: "Not found" });
}
});
// 添加文件到知识库
router.post(API.addKnowledgeBaseFilesUsingPost, (req, res) => {
const file = Mock.mock({
id: "@guid",
name: "@ctitle(5,15)",
size: "@integer(1000,1000000)",
status: "uploaded",
createdAt: "@datetime",
});
res.status(201).send(file);
});
// 获取知识生成文件详情
router.get(API.queryKnowledgeBaseFilesGet, (req, res) => {
const { keyword, page, size } = req.query;
let filteredList = fileList;
if (keyword) {
filteredList = fileList.filter((file) => file.fileName.includes(keyword));
}
const start = page * size;
const end = start + size;
const totalElements = filteredList.length;
const paginatedList = filteredList.slice(start, end);
res.send({
code: "0",
msg: "Success",
data: {
totalElements,
page,
size,
content: paginatedList,
},
});
});
router.get(API.queryKnowledgeBaseFilesByIdUsingGet, (req, res) => {
const { baseId, fileId } = req.params;
const item =
fileList.find(
(file) => file.knowledgeBaseId === baseId && file.id === fileId
) || fileItem();
res.send({
code: "0",
msg: "Success",
data: item,
});
});
// 删除知识生成文件
router.delete(API.deleteKnowledgeBaseTaskByIdUsingDelete, (req, res) => {
const { id } = req.params;
const idx = fileList.findIndex((file) => file.id === id);
if (idx >= 0) {
fileList.splice(idx, 1);
res.status(200).send({ success: true });
return;
}
res.status(404).send({ message: "Not found" });
});
};
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
// 知识库数据
function KnowledgeBaseItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.ctitle(5, 15),
description: Mock.Random.csentence(10, 30),
createdBy: Mock.Random.cname(),
updatedBy: Mock.Random.cname(),
embeddingModel: Mock.Random.pick([
"text-embedding-ada-002",
"text-embedding-3-small",
"text-embedding-3-large",
]),
chatModel: Mock.Random.pick(["gpt-3.5-turbo", "gpt-4", "gpt-4-32k"]),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const knowledgeBaseList = new Array(50).fill(null).map(KnowledgeBaseItem);
function fileItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
createdBy: Mock.Random.cname(),
updatedBy: Mock.Random.cname(),
knowledgeBaseId: Mock.Random.pick(knowledgeBaseList).id,
fileId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
fileName: Mock.Random.ctitle(5, 15),
chunkCount: Mock.Random.integer(1, 100),
metadata: {},
status: Mock.Random.pick([
"UNPROCESSED",
"PROCESSING",
"PROCESSED",
"PROCESS_FAILED",
]),
};
}
const fileList = new Array(20).fill(null).map(fileItem);
module.exports = function (router) {
// 获取知识库列表
router.post(API.queryKnowledgeBasesUsingPost, (req, res) => {
const { page = 0, size, keyword } = req.body;
let filteredList = knowledgeBaseList;
if (keyword) {
filteredList = knowledgeBaseList.filter(
(kb) => kb.name.includes(keyword) || kb.description.includes(keyword)
);
}
const start = page * size;
const end = start + size;
const totalElements = filteredList.length;
const paginatedList = filteredList.slice(start, end);
res.send({
code: "0",
msg: "Success",
data: {
totalElements,
page,
size,
content: paginatedList,
},
});
});
// 创建知识库
router.post(API.createKnowledgeBaseUsingPost, (req, res) => {
const item = KnowledgeBaseItem();
knowledgeBaseList.unshift(item);
res.status(201).send(item);
});
// 获取知识库详情
router.get(API.queryKnowledgeBaseByIdUsingGet, (req, res) => {
const id = req.params.baseId;
const item =
knowledgeBaseList.find((kb) => kb.id === id) || KnowledgeBaseItem();
res.send({
code: "0",
msg: "Success",
data: item,
});
});
// 更新知识库
router.put(API.updateKnowledgeBaseByIdUsingPut, (req, res) => {
const id = req.params.baseId;
const idx = knowledgeBaseList.findIndex((kb) => kb.id === id);
if (idx >= 0) {
knowledgeBaseList[idx] = { ...knowledgeBaseList[idx], ...req.body };
res.status(201).send(knowledgeBaseList[idx]);
} else {
res.status(404).send({ message: "Not found" });
}
});
// 删除知识库
router.delete(API.deleteKnowledgeBaseByIdUsingDelete, (req, res) => {
const id = req.params.baseId;
const idx = knowledgeBaseList.findIndex((kb) => kb.id === id);
if (idx >= 0) {
knowledgeBaseList.splice(idx, 1);
res.status(201).send({ success: true });
} else {
res.status(404).send({ message: "Not found" });
}
});
// 添加文件到知识库
router.post(API.addKnowledgeBaseFilesUsingPost, (req, res) => {
const file = Mock.mock({
id: "@guid",
name: "@ctitle(5,15)",
size: "@integer(1000,1000000)",
status: "uploaded",
createdAt: "@datetime",
});
res.status(201).send(file);
});
// 获取知识生成文件详情
router.get(API.queryKnowledgeBaseFilesGet, (req, res) => {
const { keyword, page, size } = req.query;
let filteredList = fileList;
if (keyword) {
filteredList = fileList.filter((file) => file.fileName.includes(keyword));
}
const start = page * size;
const end = start + size;
const totalElements = filteredList.length;
const paginatedList = filteredList.slice(start, end);
res.send({
code: "0",
msg: "Success",
data: {
totalElements,
page,
size,
content: paginatedList,
},
});
});
router.get(API.queryKnowledgeBaseFilesByIdUsingGet, (req, res) => {
const { baseId, fileId } = req.params;
const item =
fileList.find(
(file) => file.knowledgeBaseId === baseId && file.id === fileId
) || fileItem();
res.send({
code: "0",
msg: "Success",
data: item,
});
});
// 删除知识生成文件
router.delete(API.deleteKnowledgeBaseTaskByIdUsingDelete, (req, res) => {
const { id } = req.params;
const idx = fileList.findIndex((file) => file.id === id);
if (idx >= 0) {
fileList.splice(idx, 1);
res.status(200).send({ success: true });
return;
}
res.status(404).send({ message: "Not found" });
});
};

View File

@@ -1,150 +1,150 @@
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
// 算子标签数据
function labelItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.pick([
"数据清洗",
"特征选择",
"分类算法",
"聚类算法",
"回归分析",
"深度神经网络",
"卷积神经网络",
"循环神经网络",
"注意力机制",
"文本分析",
"图像处理",
"语音识别",
"推荐算法",
"异常检测",
"优化算法",
"集成学习",
"迁移学习",
"强化学习",
"联邦学习",
]),
usageCount: Mock.Random.integer(1, 500),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const labelList = new Array(50).fill(null).map(labelItem);
module.exports = function (router) {
router.post(API.preUploadOperatorUsingPost, (req, res) => {
res.status(201).send(Mock.Random.guid());
});
// 上传切片
router.post(API.uploadFileChunkUsingPost, (req, res) => {
// res.status(500).send({ message: "Simulated upload failure" });
res.status(201).send({ data: "success" });
});
// 取消上传
router.put(API.cancelUploadOperatorUsingPut, (req, res) => {
res.status(201).send({ data: "success" });
});
router.post(API.uploadOperatorUsingPost, (req, res) => {
res.status(201).send({
code: "0",
msg: "Upload successful",
data: {
operatorId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
// 其他返回数据
},
});
});
// 获取算子标签列表
router.get(API.queryLabelsUsingGet, (req, res) => {
const { page = 0, size = 20, keyword = "" } = req.query;
let filteredLabels = labelList;
if (keyword) {
filteredLabels = labelList.filter((label) =>
label.name.toLowerCase().includes(keyword.toLowerCase())
);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredLabels.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: pageData,
totalElements: filteredLabels.length,
totalPages: Math.ceil(filteredLabels.length / size),
size: parseInt(size),
number: parseInt(page),
},
});
});
// 创建标签
router.post(API.createLabelUsingPost, (req, res) => {
const { name } = req.body;
const newLabel = {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name,
usageCount: 0,
createdAt: new Date().toISOString(),
};
labelList.push(newLabel);
res.status(201).send({
code: "0",
msg: "Label created successfully",
data: newLabel,
});
});
// 批量删除标签
router.delete(API.deleteLabelsUsingDelete, (req, res) => {
const labelIds = req.body; // 数组形式的标签ID列表
let deletedCount = 0;
labelIds.forEach((labelId) => {
const index = labelList.findIndex((label) => label.id === labelId);
if (index !== -1) {
labelList.splice(index, 1);
deletedCount++;
}
});
res.status(204).send();
});
// 更新标签
router.put(API.updateLabelByIdUsingPut, (req, res) => {
const { id } = req.params;
const updates = req.body; // 数组形式的更新数据
updates.forEach((update) => {
const index = labelList.findIndex((label) => label.id === update.id);
if (index !== -1) {
labelList[index] = {
...labelList[index],
...update,
updatedAt: new Date().toISOString(),
};
}
});
res.send({
code: "0",
msg: "Labels updated successfully",
data: null,
});
});
};
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
// 算子标签数据
function labelItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name: Mock.Random.pick([
"数据清洗",
"特征选择",
"分类算法",
"聚类算法",
"回归分析",
"深度神经网络",
"卷积神经网络",
"循环神经网络",
"注意力机制",
"文本分析",
"图像处理",
"语音识别",
"推荐算法",
"异常检测",
"优化算法",
"集成学习",
"迁移学习",
"强化学习",
"联邦学习",
]),
usageCount: Mock.Random.integer(1, 500),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const labelList = new Array(50).fill(null).map(labelItem);
module.exports = function (router) {
router.post(API.preUploadOperatorUsingPost, (req, res) => {
res.status(201).send(Mock.Random.guid());
});
// 上传切片
router.post(API.uploadFileChunkUsingPost, (req, res) => {
// res.status(500).send({ message: "Simulated upload failure" });
res.status(201).send({ data: "success" });
});
// 取消上传
router.put(API.cancelUploadOperatorUsingPut, (req, res) => {
res.status(201).send({ data: "success" });
});
router.post(API.uploadOperatorUsingPost, (req, res) => {
res.status(201).send({
code: "0",
msg: "Upload successful",
data: {
operatorId: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
// 其他返回数据
},
});
});
// 获取算子标签列表
router.get(API.queryLabelsUsingGet, (req, res) => {
const { page = 0, size = 20, keyword = "" } = req.query;
let filteredLabels = labelList;
if (keyword) {
filteredLabels = labelList.filter((label) =>
label.name.toLowerCase().includes(keyword.toLowerCase())
);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredLabels.slice(startIndex, endIndex);
res.send({
code: "0",
msg: "Success",
data: {
content: pageData,
totalElements: filteredLabels.length,
totalPages: Math.ceil(filteredLabels.length / size),
size: parseInt(size),
number: parseInt(page),
},
});
});
// 创建标签
router.post(API.createLabelUsingPost, (req, res) => {
const { name } = req.body;
const newLabel = {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
name,
usageCount: 0,
createdAt: new Date().toISOString(),
};
labelList.push(newLabel);
res.status(201).send({
code: "0",
msg: "Label created successfully",
data: newLabel,
});
});
// 批量删除标签
router.delete(API.deleteLabelsUsingDelete, (req, res) => {
const labelIds = req.body; // 数组形式的标签ID列表
let deletedCount = 0;
labelIds.forEach((labelId) => {
const index = labelList.findIndex((label) => label.id === labelId);
if (index !== -1) {
labelList.splice(index, 1);
deletedCount++;
}
});
res.status(204).send();
});
// 更新标签
router.put(API.updateLabelByIdUsingPut, (req, res) => {
const { id } = req.params;
const updates = req.body; // 数组形式的更新数据
updates.forEach((update) => {
const index = labelList.findIndex((label) => label.id === update.id);
if (index !== -1) {
labelList[index] = {
...labelList[index],
...update,
updatedAt: new Date().toISOString(),
};
}
});
res.send({
code: "0",
msg: "Labels updated successfully",
data: null,
});
});
};

View File

@@ -1,177 +1,177 @@
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
// 算子标签数据
function ModelItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
modelName: Mock.Random.pick([
"数据清洗",
"特征选择",
"分类算法",
"聚类算法",
"回归分析",
"深度神经网络",
"卷积神经网络",
"循环神经网络",
"注意力机制",
"文本分析",
"图像处理",
"语音识别",
"推荐算法",
"异常检测",
"优化算法",
"集成学习",
"迁移学习",
"强化学习",
"联邦学习",
]),
provider: Mock.Random.pick([
"OpenAI",
"Anthropic",
"Cohere",
"AI21 Labs",
"Hugging Face",
"Google Cloud AI",
"Microsoft Azure AI",
"Amazon Web Services AI",
"IBM Watson",
"Alibaba Cloud AI",
]),
type: Mock.Random.pick(["CHAT", "EMBEDDING"]),
usageCount: Mock.Random.integer(1, 500),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const modelList = new Array(50).fill(null).map(ModelItem);
function ProviderItem(provider) {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
provider,
baseUrl: Mock.Random.url("https") + "/v1/models",
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const ProviderList = [
"OpenAI",
"Anthropic",
"Cohere",
"AI21 Labs",
"Hugging Face",
"Google Cloud AI",
"Microsoft Azure AI",
"Amazon Web Services AI",
"IBM Watson",
"Alibaba Cloud AI",
].map(ProviderItem);
module.exports = function (router) {
// 获取模型列表
router.get(API.queryModelsUsingGet, (req, res) => {
const {
page = 0,
size = 20,
keyword = "",
provider = "",
type = "",
} = req.query;
let filteredModels = modelList;
if (keyword) {
filteredModels = modelList.filter((model) =>
model.modelName.toLowerCase().includes(keyword.toLowerCase())
);
}
if (provider && provider !== "all") {
filteredModels = filteredModels.filter(
(model) => model.provider === provider
);
}
if (type && type !== "all") {
filteredModels = filteredModels.filter((model) => model.type === type);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredModels.slice(startIndex, endIndex);
res.status(201).send({
code: "0",
msg: "Success",
data: {
content: pageData,
totalElements: filteredModels.length,
totalPages: Math.ceil(filteredModels.length / size),
size: parseInt(size),
number: parseInt(page),
},
});
});
// 获取模型提供商列表
router.get(API.queryProvidersUsingGet, (req, res) => {
res.status(201).send({
code: "0",
msg: "success",
data: ProviderList,
});
});
// 创建模型
router.post(API.createModelUsingPost, (req, res) => {
const { ...modelData } = req.body;
const newModel = {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
...modelData,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
modelList.unshift(newModel);
res.status(201).send({
code: "0",
msg: "success",
data: newModel,
});
});
// 删除模型
router.delete(API.deleteModelUsingDelete, (req, res) => {
const { id } = req.params;
const index = modelList.findIndex((model) => model.id === id);
if (index !== -1) {
modelList.splice(index, 1);
}
res.status(204).send({
code: "0",
msg: "success",
data: null,
});
});
// 更新模型
router.put(API.updateModelUsingPut, (req, res) => {
const { id, ...update } = req.params;
const index = modelList.findIndex((model) => model.id === id);
if (index !== -1) {
modelList[index] = {
...modelList[index],
...update,
updatedAt: new Date().toISOString(),
};
}
res.status(201).send({
code: "0",
msg: "success",
data: null,
});
});
};
const Mock = require("mockjs");
const API = require("../mock-apis.cjs");
// 算子标签数据
function ModelItem() {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
modelName: Mock.Random.pick([
"数据清洗",
"特征选择",
"分类算法",
"聚类算法",
"回归分析",
"深度神经网络",
"卷积神经网络",
"循环神经网络",
"注意力机制",
"文本分析",
"图像处理",
"语音识别",
"推荐算法",
"异常检测",
"优化算法",
"集成学习",
"迁移学习",
"强化学习",
"联邦学习",
]),
provider: Mock.Random.pick([
"OpenAI",
"Anthropic",
"Cohere",
"AI21 Labs",
"Hugging Face",
"Google Cloud AI",
"Microsoft Azure AI",
"Amazon Web Services AI",
"IBM Watson",
"Alibaba Cloud AI",
]),
type: Mock.Random.pick(["CHAT", "EMBEDDING"]),
usageCount: Mock.Random.integer(1, 500),
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
updatedAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const modelList = new Array(50).fill(null).map(ModelItem);
function ProviderItem(provider) {
return {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
provider,
baseUrl: Mock.Random.url("https") + "/v1/models",
createdAt: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"),
};
}
const ProviderList = [
"OpenAI",
"Anthropic",
"Cohere",
"AI21 Labs",
"Hugging Face",
"Google Cloud AI",
"Microsoft Azure AI",
"Amazon Web Services AI",
"IBM Watson",
"Alibaba Cloud AI",
].map(ProviderItem);
module.exports = function (router) {
// 获取模型列表
router.get(API.queryModelsUsingGet, (req, res) => {
const {
page = 0,
size = 20,
keyword = "",
provider = "",
type = "",
} = req.query;
let filteredModels = modelList;
if (keyword) {
filteredModels = modelList.filter((model) =>
model.modelName.toLowerCase().includes(keyword.toLowerCase())
);
}
if (provider && provider !== "all") {
filteredModels = filteredModels.filter(
(model) => model.provider === provider
);
}
if (type && type !== "all") {
filteredModels = filteredModels.filter((model) => model.type === type);
}
const startIndex = page * size;
const endIndex = startIndex + parseInt(size);
const pageData = filteredModels.slice(startIndex, endIndex);
res.status(201).send({
code: "0",
msg: "Success",
data: {
content: pageData,
totalElements: filteredModels.length,
totalPages: Math.ceil(filteredModels.length / size),
size: parseInt(size),
number: parseInt(page),
},
});
});
// 获取模型提供商列表
router.get(API.queryProvidersUsingGet, (req, res) => {
res.status(201).send({
code: "0",
msg: "success",
data: ProviderList,
});
});
// 创建模型
router.post(API.createModelUsingPost, (req, res) => {
const { ...modelData } = req.body;
const newModel = {
id: Mock.Random.guid().replace(/[^a-zA-Z0-9]/g, ""),
...modelData,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
modelList.unshift(newModel);
res.status(201).send({
code: "0",
msg: "success",
data: newModel,
});
});
// 删除模型
router.delete(API.deleteModelUsingDelete, (req, res) => {
const { id } = req.params;
const index = modelList.findIndex((model) => model.id === id);
if (index !== -1) {
modelList.splice(index, 1);
}
res.status(204).send({
code: "0",
msg: "success",
data: null,
});
});
// 更新模型
router.put(API.updateModelUsingPut, (req, res) => {
const { id, ...update } = req.params;
const index = modelList.findIndex((model) => model.id === id);
if (index !== -1) {
modelList[index] = {
...modelList[index],
...update,
updatedAt: new Date().toISOString(),
};
}
res.status(201).send({
code: "0",
msg: "success",
data: null,
});
});
};

View File

@@ -1,58 +1,58 @@
const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const bodyParser = require('body-parser');
const { genExpressSession } = require('./mock-core/session-helper.cjs');
const {
setHeader,
sendJSON,
strongMatch,
errorHandle,
} = require('./mock-middleware/index.cjs');
const { loadAllMockModules } = require('./mock-core/module-loader.cjs');
const { log } = require('./mock-core/util.cjs');
const app = express();
const router = express.Router();
const argv = require('minimist')(process.argv.slice(2));
const deployUrl = argv['deploy-url'] || '/';
const deployPath = argv['deploy-path'] || '/';
const port = argv.port || 8002;
const env = argv.env || 'development';
// app静态文件实际目录
const deployAppPath = path.join(__dirname, deployPath);
preStartCheck(deployAppPath);
app.use(setHeader);
// 提供静态文件服务
app.use(deployUrl, express.static(deployAppPath));
app.use(bodyParser.json({limit: '1mb'}));
app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }));
app.use(sendJSON);
app.use(strongMatch);
app.use(genExpressSession());
const mockDir = path.join(__dirname, '/mock-seed');
loadAllMockModules(router, mockDir);
app.use(deployUrl, router);
app.use(errorHandle);
app.get('/', (req, res) => {
res.sendFile('default response', { root: deployAppPath });
});
app.listen(port, function() {
log(`Mock server is running at http://localhost:${port}${deployUrl} in ${env} mode`);
})
function preStartCheck(deployAppPath) {
if(!fs.existsSync(deployAppPath)) {
log(`Error: The path ${deployAppPath} does not exist. Please build the frontend application first.`, 'error');
process.exit(1);
}
const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const bodyParser = require('body-parser');
const { genExpressSession } = require('./mock-core/session-helper.cjs');
const {
setHeader,
sendJSON,
strongMatch,
errorHandle,
} = require('./mock-middleware/index.cjs');
const { loadAllMockModules } = require('./mock-core/module-loader.cjs');
const { log } = require('./mock-core/util.cjs');
const app = express();
const router = express.Router();
const argv = require('minimist')(process.argv.slice(2));
const deployUrl = argv['deploy-url'] || '/';
const deployPath = argv['deploy-path'] || '/';
const port = argv.port || 8002;
const env = argv.env || 'development';
// app静态文件实际目录
const deployAppPath = path.join(__dirname, deployPath);
preStartCheck(deployAppPath);
app.use(setHeader);
// 提供静态文件服务
app.use(deployUrl, express.static(deployAppPath));
app.use(bodyParser.json({limit: '1mb'}));
app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }));
app.use(sendJSON);
app.use(strongMatch);
app.use(genExpressSession());
const mockDir = path.join(__dirname, '/mock-seed');
loadAllMockModules(router, mockDir);
app.use(deployUrl, router);
app.use(errorHandle);
app.get('/', (req, res) => {
res.sendFile('default response', { root: deployAppPath });
});
app.listen(port, function() {
log(`Mock server is running at http://localhost:${port}${deployUrl} in ${env} mode`);
})
function preStartCheck(deployAppPath) {
if(!fs.existsSync(deployAppPath)) {
log(`Error: The path ${deployAppPath} does not exist. Please build the frontend application first.`, 'error');
process.exit(1);
}
}

View File

@@ -1,22 +1,22 @@
{
"restartable": "rs",
"ignore": [
".git",
"node_modules/**/node_modules",
"dist",
"build",
"*.test.js",
"*.spec.js"
],
"verbose": true,
"watch": ["*.cjs"],
"exec": "node --inspect=0.0.0.0:9229 mock.cjs",
"ext": "js,cjs,json",
"execMap": {
"js": "node --harmony"
},
"env": {
"NODE_ENV": "development"
},
"signal": "SIGTERM"
}
{
"restartable": "rs",
"ignore": [
".git",
"node_modules/**/node_modules",
"dist",
"build",
"*.test.js",
"*.spec.js"
],
"verbose": true,
"watch": ["*.cjs"],
"exec": "node --inspect=0.0.0.0:9229 mock.cjs",
"ext": "js,cjs,json",
"execMap": {
"js": "node --harmony"
},
"env": {
"NODE_ENV": "development"
},
"signal": "SIGTERM"
}

View File

@@ -1,209 +1,209 @@
// Add mock files data
export const mockFiles = [
{ id: "file1", name: "dataset_part_001.jsonl", size: "2.5MB", type: "JSONL" },
{ id: "file2", name: "dataset_part_002.jsonl", size: "2.3MB", type: "JSONL" },
{ id: "file3", name: "dataset_part_003.jsonl", size: "2.7MB", type: "JSONL" },
{ id: "file4", name: "training_data.txt", size: "1.8MB", type: "TXT" },
{ id: "file5", name: "validation_set.csv", size: "856KB", type: "CSV" },
{ id: "file6", name: "test_samples.json", size: "1.2MB", type: "JSON" },
{ id: "file7", name: "raw_text_001.txt", size: "3.1MB", type: "TXT" },
{ id: "file8", name: "raw_text_002.txt", size: "2.9MB", type: "TXT" },
];
export const mockSynthesisTasks: SynthesisTask[] = [
{
id: 1,
name: "文字生成问答对_判断题",
type: "qa",
status: "completed",
progress: 100,
sourceDataset: "orig_20250724_64082",
targetCount: 1000,
generatedCount: 1000,
createdAt: "2025-01-20",
template: "判断题生成模板",
estimatedTime: "已完成",
quality: 95,
},
{
id: 2,
name: "知识蒸馏数据集",
type: "distillation",
status: "running",
progress: 65,
sourceDataset: "teacher_model_outputs",
targetCount: 5000,
generatedCount: 3250,
createdAt: "2025-01-22",
template: "蒸馏模板v2",
estimatedTime: "剩余 15 分钟",
quality: 88,
},
{
id: 3,
name: "多模态对话生成",
type: "multimodal",
status: "failed",
progress: 25,
sourceDataset: "image_text_pairs",
targetCount: 2000,
generatedCount: 500,
createdAt: "2025-01-23",
template: "多模态对话模板",
errorMessage: "模型API调用失败,请检查配置",
},
{
id: 4,
name: "金融问答数据生成",
type: "qa",
status: "pending",
progress: 0,
sourceDataset: "financial_qa_dataset",
targetCount: 800,
generatedCount: 0,
createdAt: "2025-01-24",
template: "金融问答模板",
estimatedTime: "等待开始",
quality: 0,
},
{
id: 5,
name: "医疗文本蒸馏",
type: "distillation",
status: "paused",
progress: 45,
sourceDataset: "medical_corpus",
targetCount: 3000,
generatedCount: 1350,
createdAt: "2025-01-21",
template: "医疗蒸馏模板",
estimatedTime: "已暂停",
quality: 92,
},
];
export const mockTemplates: Template[] = [
{
id: 1,
name: "判断题生成模板",
type: "preset",
category: "问答对生成",
prompt: `根据给定的文本内容,生成一个判断题。
文本内容:{text}
请按照以下格式生成:
1. 判断题:[基于文本内容的判断题]
2. 答案:[对/错]
3. 解释:[简要解释为什么这个答案是正确的]
要求:
- 判断题应该基于文本的核心内容
- 答案必须明确且有依据
- 解释要简洁清晰`,
variables: ["text"],
description: "根据文本内容生成判断题,适用于教育和培训场景",
usageCount: 156,
lastUsed: "2025-01-20",
quality: 95,
},
{
id: 2,
name: "选择题生成模板",
type: "preset",
category: "问答对生成",
prompt: `基于以下文本,创建一个多选题:
{text}
请按照以下格式生成:
问题:[基于文本的问题]
A. [选项A]
B. [选项B]
C. [选项C]
D. [选项D]
正确答案:[A/B/C/D]
解析:[详细解释]
要求:
- 问题要有一定难度
- 选项要有迷惑性
- 正确答案要有充分依据`,
variables: ["text"],
description: "生成多选题的标准模板,适用于考试和评估",
usageCount: 89,
lastUsed: "2025-01-19",
quality: 92,
},
{
id: 3,
name: "知识蒸馏模板",
type: "preset",
category: "蒸馏数据集",
prompt: `作为学生模型,学习教师模型的输出:
输入:{input}
教师输出:{teacher_output}
请模仿教师模型的推理过程和输出格式,生成相似质量的回答。
要求:
- 保持教师模型的推理逻辑
- 输出格式要一致
- 质量要接近教师模型水平`,
variables: ["input", "teacher_output"],
description: "用于知识蒸馏的模板,帮助小模型学习大模型的能力",
usageCount: 234,
lastUsed: "2025-01-22",
quality: 88,
},
{
id: 4,
name: "金融问答模板",
type: "custom",
category: "问答对生成",
prompt: `基于金融领域知识,生成专业问答对:
参考内容:{content}
生成格式:
问题:[专业的金融问题]
答案:[准确的专业回答]
关键词:[相关金融术语]
要求:
- 问题具有实用性
- 答案准确专业
- 符合金融行业标准`,
variables: ["content"],
description: "专门用于金融领域的问答对生成",
usageCount: 45,
lastUsed: "2025-01-18",
quality: 89,
},
{
id: 5,
name: "医疗蒸馏模板",
type: "custom",
category: "蒸馏数据集",
prompt: `医疗知识蒸馏模板:
原始医疗文本:{medical_text}
专家标注:{expert_annotation}
生成医疗知识点:
1. 核心概念:[提取关键医疗概念]
2. 临床意义:[说明临床应用价值]
3. 注意事项:[重要提醒和禁忌]
要求:
- 确保医疗信息准确性
- 遵循医疗伦理规范
- 适合医学教育使用`,
variables: ["medical_text", "expert_annotation"],
description: "医疗领域专用的知识蒸馏模板",
usageCount: 67,
lastUsed: "2025-01-21",
quality: 94,
},
];
// Add mock files data
export const mockFiles = [
{ id: "file1", name: "dataset_part_001.jsonl", size: "2.5MB", type: "JSONL" },
{ id: "file2", name: "dataset_part_002.jsonl", size: "2.3MB", type: "JSONL" },
{ id: "file3", name: "dataset_part_003.jsonl", size: "2.7MB", type: "JSONL" },
{ id: "file4", name: "training_data.txt", size: "1.8MB", type: "TXT" },
{ id: "file5", name: "validation_set.csv", size: "856KB", type: "CSV" },
{ id: "file6", name: "test_samples.json", size: "1.2MB", type: "JSON" },
{ id: "file7", name: "raw_text_001.txt", size: "3.1MB", type: "TXT" },
{ id: "file8", name: "raw_text_002.txt", size: "2.9MB", type: "TXT" },
];
export const mockSynthesisTasks: SynthesisTask[] = [
{
id: 1,
name: "文字生成问答对_判断题",
type: "qa",
status: "completed",
progress: 100,
sourceDataset: "orig_20250724_64082",
targetCount: 1000,
generatedCount: 1000,
createdAt: "2025-01-20",
template: "判断题生成模板",
estimatedTime: "已完成",
quality: 95,
},
{
id: 2,
name: "知识蒸馏数据集",
type: "distillation",
status: "running",
progress: 65,
sourceDataset: "teacher_model_outputs",
targetCount: 5000,
generatedCount: 3250,
createdAt: "2025-01-22",
template: "蒸馏模板v2",
estimatedTime: "剩余 15 分钟",
quality: 88,
},
{
id: 3,
name: "多模态对话生成",
type: "multimodal",
status: "failed",
progress: 25,
sourceDataset: "image_text_pairs",
targetCount: 2000,
generatedCount: 500,
createdAt: "2025-01-23",
template: "多模态对话模板",
errorMessage: "模型API调用失败,请检查配置",
},
{
id: 4,
name: "金融问答数据生成",
type: "qa",
status: "pending",
progress: 0,
sourceDataset: "financial_qa_dataset",
targetCount: 800,
generatedCount: 0,
createdAt: "2025-01-24",
template: "金融问答模板",
estimatedTime: "等待开始",
quality: 0,
},
{
id: 5,
name: "医疗文本蒸馏",
type: "distillation",
status: "paused",
progress: 45,
sourceDataset: "medical_corpus",
targetCount: 3000,
generatedCount: 1350,
createdAt: "2025-01-21",
template: "医疗蒸馏模板",
estimatedTime: "已暂停",
quality: 92,
},
];
export const mockTemplates: Template[] = [
{
id: 1,
name: "判断题生成模板",
type: "preset",
category: "问答对生成",
prompt: `根据给定的文本内容,生成一个判断题。
文本内容:{text}
请按照以下格式生成:
1. 判断题:[基于文本内容的判断题]
2. 答案:[对/错]
3. 解释:[简要解释为什么这个答案是正确的]
要求:
- 判断题应该基于文本的核心内容
- 答案必须明确且有依据
- 解释要简洁清晰`,
variables: ["text"],
description: "根据文本内容生成判断题,适用于教育和培训场景",
usageCount: 156,
lastUsed: "2025-01-20",
quality: 95,
},
{
id: 2,
name: "选择题生成模板",
type: "preset",
category: "问答对生成",
prompt: `基于以下文本,创建一个多选题:
{text}
请按照以下格式生成:
问题:[基于文本的问题]
A. [选项A]
B. [选项B]
C. [选项C]
D. [选项D]
正确答案:[A/B/C/D]
解析:[详细解释]
要求:
- 问题要有一定难度
- 选项要有迷惑性
- 正确答案要有充分依据`,
variables: ["text"],
description: "生成多选题的标准模板,适用于考试和评估",
usageCount: 89,
lastUsed: "2025-01-19",
quality: 92,
},
{
id: 3,
name: "知识蒸馏模板",
type: "preset",
category: "蒸馏数据集",
prompt: `作为学生模型,学习教师模型的输出:
输入:{input}
教师输出:{teacher_output}
请模仿教师模型的推理过程和输出格式,生成相似质量的回答。
要求:
- 保持教师模型的推理逻辑
- 输出格式要一致
- 质量要接近教师模型水平`,
variables: ["input", "teacher_output"],
description: "用于知识蒸馏的模板,帮助小模型学习大模型的能力",
usageCount: 234,
lastUsed: "2025-01-22",
quality: 88,
},
{
id: 4,
name: "金融问答模板",
type: "custom",
category: "问答对生成",
prompt: `基于金融领域知识,生成专业问答对:
参考内容:{content}
生成格式:
问题:[专业的金融问题]
答案:[准确的专业回答]
关键词:[相关金融术语]
要求:
- 问题具有实用性
- 答案准确专业
- 符合金融行业标准`,
variables: ["content"],
description: "专门用于金融领域的问答对生成",
usageCount: 45,
lastUsed: "2025-01-18",
quality: 89,
},
{
id: 5,
name: "医疗蒸馏模板",
type: "custom",
category: "蒸馏数据集",
prompt: `医疗知识蒸馏模板:
原始医疗文本:{medical_text}
专家标注:{expert_annotation}
生成医疗知识点:
1. 核心概念:[提取关键医疗概念]
2. 临床意义:[说明临床应用价值]
3. 注意事项:[重要提醒和禁忌]
要求:
- 确保医疗信息准确性
- 遵循医疗伦理规范
- 适合医学教育使用`,
variables: ["medical_text", "expert_annotation"],
description: "医疗领域专用的知识蒸馏模板",
usageCount: 67,
lastUsed: "2025-01-21",
quality: 94,
},
];

View File

@@ -1,480 +1,480 @@
import type React from "react";
import { useState, useRef, useEffect } from "react";
import { Card, Input, Button, Badge } from "antd";
import { HomeOutlined } from "@ant-design/icons";
import {
MessageSquare,
Send,
Bot,
User,
Sparkles,
Database,
BarChart3,
Settings,
Zap,
CheckCircle,
Clock,
Download,
ArrowLeft,
} from "lucide-react";
import { useNavigate } from "react-router";
import DevelopmentInProgress from "@/components/DevelopmentInProgress";
interface Message {
id: string;
type: "user" | "assistant";
content: string;
timestamp: Date;
actions?: Array<{
type:
| "create_dataset"
| "run_analysis"
| "start_synthesis"
| "export_report";
label: string;
data?: any;
}>;
status?: "pending" | "completed" | "error";
}
interface QuickAction {
id: string;
label: string;
icon: any;
prompt: string;
category: string;
}
const quickActions: QuickAction[] = [
{
id: "create_dataset",
label: "创建数据集",
icon: Database,
prompt: "帮我创建一个新的数据集",
category: "数据管理",
},
{
id: "analyze_quality",
label: "质量分析",
icon: BarChart3,
prompt: "分析我的数据集质量",
category: "数据评估",
},
{
id: "start_synthesis",
label: "数据合成",
icon: Sparkles,
prompt: "启动数据合成任务",
category: "数据合成",
},
{
id: "process_data",
label: "数据清洗",
icon: Settings,
prompt: "对数据集进行预处理",
category: "数据清洗",
},
{
id: "export_report",
label: "导出报告",
icon: Download,
prompt: "导出最新的分析报告",
category: "报告导出",
},
{
id: "check_status",
label: "查看状态",
icon: Clock,
prompt: "查看所有任务的运行状态",
category: "状态查询",
},
];
const mockResponses = {
: {
content:
"我来帮您创建一个新的数据集。请告诉我以下信息:\n\n1. 数据集名称\n2. 数据类型(图像、文本、问答对等)\n3. 预期数据量\n4. 数据来源\n\n您也可以直接说出您的需求,我会为您推荐最适合的配置。",
actions: [
{ type: "create_dataset", label: "开始创建", data: { step: "config" } },
],
},
: {
content:
"正在为您分析数据集质量...\n\n📊 **分析结果概览:**\n- 图像分类数据集:质量分 92/100\n- 问答对数据集:质量分 87/100\n- 多模态数据集:质量分 78/100\n\n🔍 **发现的主要问题:**\n- 23个重复图像\n- 156个格式不正确的问答对\n- 78个图文不匹配项\n\n💡 **改进建议:**\n- 建议进行去重处理\n- 优化问答对格式\n- 重新标注图文匹配项",
actions: [
{
type: "run_analysis",
label: "查看详细报告",
data: { type: "detailed" },
},
],
},
: {
content:
"我可以帮您启动数据合成任务。目前支持以下合成类型:\n\n🖼️ **图像数据合成**\n- 数据增强(旋转、翻转、亮度调整)\n- 风格迁移\n- GAN生成\n\n📝 **文本数据合成**\n- 同义词替换\n- 回译增强\n- GPT生成\n\n❓ **问答对合成**\n- 基于知识库生成\n- 模板变换\n- 多轮对话生成\n\n请告诉我您需要合成什么类型的数据,以及目标数量。",
actions: [
{
type: "start_synthesis",
label: "配置合成任务",
data: { step: "config" },
},
],
},
: {
content:
"正在为您准备最新的分析报告...\n\n📋 **可用报告:**\n- 数据质量评估报告(PDF)\n- 数据分布统计报告(Excel)\n- 模型性能评估报告(PDF)\n- 偏见检测报告(PDF)\n- 综合分析报告(PDF + Excel)\n\n✅ 报告已生成完成,您可以选择下载格式。",
actions: [
{ type: "export_report", label: "下载报告", data: { format: "pdf" } },
],
},
: {
content:
"📊 **当前任务状态概览:**\n\n🟢 **运行中的任务:**\n- 问答对生成任务:65% 完成\n- 图像质量分析:运行中\n- 知识库构建:等待中\n\n✅ **已完成的任务:**\n- 图像分类数据集创建:已完成\n- PDF文档提取:已完成\n- 训练集配比任务:已完成\n\n⚠️ **需要关注的任务:**\n- 多模态数据合成:暂停(需要用户确认参数)\n\n所有任务运行正常,预计2小时内全部完成。",
actions: [],
},
};
export default function AgentPage() {
return <DevelopmentInProgress />;
const navigate = useNavigate();
const [messages, setMessages] = useState<Message[]>([
{
id: "welcome",
type: "assistant",
content:
"👋 您好!我是 Data Agent,您的AI数据助手。\n\n我可以帮您:\n• 创建和管理数据集\n• 分析数据质量\n• 启动处理任务\n• 生成分析报告\n• 回答数据相关问题\n\n请告诉我您需要什么帮助,或者点击下方的快捷操作开始。",
timestamp: new Date(),
},
]);
const [inputValue, setInputValue] = useState("");
const [isTyping, setIsTyping] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<any>(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(() => {
scrollToBottom();
}, [messages]);
const handleSendMessage = async (content: string) => {
if (!content.trim()) return;
const userMessage: Message = {
id: Date.now().toString(),
type: "user",
content: content.trim(),
timestamp: new Date(),
};
setMessages((prev) => [...prev, userMessage]);
setInputValue("");
setIsTyping(true);
// 模拟AI响应
setTimeout(() => {
const response = generateResponse(content);
const assistantMessage: Message = {
id: (Date.now() + 1).toString(),
type: "assistant",
content: response.content,
timestamp: new Date(),
actions: response.actions,
};
setMessages((prev) => [...prev, assistantMessage]);
setIsTyping(false);
}, 1500);
};
const generateResponse = (
input: string
): { content: string; actions?: any[] } => {
const lowerInput = input.toLowerCase();
if (lowerInput.includes("创建") && lowerInput.includes("数据集")) {
return mockResponses["创建数据集"];
} else if (lowerInput.includes("质量") || lowerInput.includes("分析")) {
return mockResponses["质量分析"];
} else if (lowerInput.includes("合成") || lowerInput.includes("生成")) {
return mockResponses["数据合成"];
} else if (lowerInput.includes("导出") || lowerInput.includes("报告")) {
return mockResponses["导出报告"];
} else if (lowerInput.includes("状态") || lowerInput.includes("任务")) {
return mockResponses["查看状态"];
} else if (lowerInput.includes("你好") || lowerInput.includes("帮助")) {
return {
content:
"很高兴为您服务!我是专门为数据集管理设计的AI助手。\n\n我的主要能力包括:\n\n🔧 **数据集操作**\n- 创建、导入、导出数据集\n- 数据预处理和清洗\n- 批量操作和自动化\n\n📊 **智能分析**\n- 数据质量评估\n- 分布统计分析\n- 性能和偏见检测\n\n🤖 **AI增强**\n- 智能数据合成\n- 自动标注建议\n- 知识库构建\n\n请告诉我您的具体需求,我会为您提供最合适的解决方案!",
};
} else {
return {
content: `我理解您想要「${input}」。让我为您分析一下...\n\n基于您的需求,我建议:\n\n1. 首先确认具体的操作目标\n2. 选择合适的数据集和参数\n3. 执行相应的处理流程\n\n您可以提供更多详细信息,或者选择下方的快捷操作来开始。如果需要帮助,请说"帮助"获取完整功能列表。`,
actions: [
{ type: "run_analysis", label: "开始分析", data: { query: input } },
],
};
}
};
const handleQuickAction = (action: QuickAction) => {
handleSendMessage(action.prompt);
};
const handleActionClick = (action: any) => {
const actionMessage: Message = {
id: Date.now().toString(),
type: "assistant",
content: `✅ 正在执行「${action.label}」...\n\n操作已启动,您可以在相应的功能模块中查看详细进度。`,
timestamp: new Date(),
status: "completed",
};
setMessages((prev) => [...prev, actionMessage]);
};
const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage(inputValue);
}
};
const formatMessage = (content: string) => {
return content.split("\n").map((line, index) => (
<div key={index} className="mb-1">
{line || <br />}
</div>
));
};
const onBack = () => {
navigate("/");
};
return (
<div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50">
<div className="h-screen flex flex-col">
{/* Header */}
<div className="bg-gradient-to-r from-purple-500 to-pink-500 text-white p-6">
<div className="max-w-7xl mx-auto">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-white/20 rounded-lg flex items-center justify-center">
<MessageSquare className="w-6 h-6" />
</div>
<div>
<h1 className="text-2xl font-bold">Data Agent</h1>
<p className="text-purple-100">
AI驱动的智能数据助手
</p>
</div>
</div>
<Button
type="default"
icon={<ArrowLeft className="w-4 h-4 mr-2" />}
onClick={onBack}
className="bg-white/10 border-white/20 text-white hover:bg-white/20 hover:border-white/30"
>
</Button>
</div>
</div>
</div>
<div className="flex-1 max-w-7xl mx-auto h-full w-full p-6">
<div className="h-full flex gap-6">
{/* Chat Area */}
<div className="lg:col-span-3 flex flex-1 flex-col h-full">
<div className="flex-1 flex flex-col h-full shadow-lg">
<div className="pb-3 bg-white rounded-t-lg">
<div className="flex items-center justify-between p-4">
<span className="text-lg font-semibold"></span>
<div>
<span className="w-2 h-2 bg-green-500 rounded-full mr-1 inline-block" />
线
</div>
</div>
</div>
<div className="flex-1 flex flex-col justify-between h-full p-0 min-h-0">
{/* Messages */}
<div className="flex-1 overflow-y-auto p-6 bg-white">
<div className="space-y-4 pb-4">
{messages.map((message) => (
<div
key={message.id}
className={`flex gap-3 ${
message.type === "user"
? "justify-end"
: "justify-start"
}`}
>
{message.type === "assistant" && (
<div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center flex-shrink-0">
<Bot className="w-4 h-4 text-white" />
</div>
)}
<div
className={`max-w-[80%] rounded-lg px-4 py-3 ${
message.type === "user"
? "bg-blue-500 text-white"
: "bg-white text-gray-900 shadow-sm border border-gray-100"
}`}
>
<div className="text-sm whitespace-pre-wrap">
{formatMessage(message.content)}
</div>
{message.actions && message.actions.length > 0 && (
<div className="mt-3 space-y-2">
{message.actions.map((action, index) => (
<Button
key={index}
type="default"
size="small"
className="mr-2 mb-2"
onClick={() => handleActionClick(action)}
>
{action.label}
</Button>
))}
</div>
)}
<div className="text-xs opacity-70 mt-2">
{message.timestamp.toLocaleTimeString()}
</div>
</div>
{message.type === "user" && (
<div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0">
<User className="w-4 h-4 text-white" />
</div>
)}
</div>
))}
{isTyping && (
<div className="flex gap-3 justify-start">
<div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
<Bot className="w-4 h-4 text-white" />
</div>
<div className="bg-white rounded-lg px-4 py-3 shadow-sm border border-gray-100">
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce delay-100"></div>
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce delay-200"></div>
</div>
</div>
</div>
)}
</div>
<div ref={messagesEndRef} />
</div>
{/* Input Area */}
<div className="border-t border-gray-200 p-4 bg-white rounded-b-lg">
<div className="flex gap-2">
<Input
ref={inputRef}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyPress}
placeholder="输入您的需求,例如:创建一个图像分类数据集..."
disabled={isTyping}
/>
<Button
type="primary"
onClick={() => handleSendMessage(inputValue)}
disabled={!inputValue.trim() || isTyping}
className="bg-gradient-to-r from-purple-400 to-pink-400 border-none hover:from-purple-500 hover:to-pink-500"
>
<Send className="w-4 h-4" />
</Button>
</div>
</div>
</div>
</div>
</div>
{/* Quick Actions Sidebar */}
<div className="w-72 flex flex-col gap-6">
<Card className="shadow-lg">
<div className="">
<span className="text-lg font-semibold"></span>
<div className="text-sm text-gray-500">
</div>
</div>
<div className="space-y-2 p-4">
{quickActions.map((action) => (
<Button
key={action.id}
type="default"
className="w-full justify-start h-auto p-3 text-left"
onClick={() => handleQuickAction(action)}
>
<action.icon className="w-4 h-4 mr-2 flex-shrink-0" />
<div className="text-left">
<div className="font-medium text-sm">
{action.label}
</div>
</div>
</Button>
))}
</div>
</Card>
<Card className="shadow-lg">
<div className="pb-3">
<span className="text-lg font-semibold"></span>
</div>
<div className="space-y-3 p-4 pt-0">
<div className="flex items-center gap-2 text-sm">
<CheckCircle className="w-4 h-4 text-green-500" />
<span>AI服务正常</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Clock className="w-4 h-4 text-blue-500" />
<span>3</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Database className="w-4 h-4 text-purple-500" />
<span>12</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Zap className="w-4 h-4 text-orange-500" />
<span>响应时间: 0.8s</span>
</div>
</div>
</Card>
<Card className="shadow-lg">
<div className="pb-3">
<span className="text-lg font-semibold">使</span>
</div>
<div className="space-y-2 text-sm text-gray-600 p-4 pt-0">
<div>💡 </div>
<div>🔍 </div>
<div>📊 </div>
<div> 使</div>
</div>
</Card>
<Card className="shadow-lg">
<div className="pt-6 p-4">
<Button
type="default"
className="w-full"
icon={<HomeOutlined />}
onClick={onBack}
>
</Button>
</div>
</Card>
</div>
</div>
</div>
</div>
</div>
);
}
import type React from "react";
import { useState, useRef, useEffect } from "react";
import { Card, Input, Button, Badge } from "antd";
import { HomeOutlined } from "@ant-design/icons";
import {
MessageSquare,
Send,
Bot,
User,
Sparkles,
Database,
BarChart3,
Settings,
Zap,
CheckCircle,
Clock,
Download,
ArrowLeft,
} from "lucide-react";
import { useNavigate } from "react-router";
import DevelopmentInProgress from "@/components/DevelopmentInProgress";
interface Message {
id: string;
type: "user" | "assistant";
content: string;
timestamp: Date;
actions?: Array<{
type:
| "create_dataset"
| "run_analysis"
| "start_synthesis"
| "export_report";
label: string;
data?: any;
}>;
status?: "pending" | "completed" | "error";
}
interface QuickAction {
id: string;
label: string;
icon: any;
prompt: string;
category: string;
}
const quickActions: QuickAction[] = [
{
id: "create_dataset",
label: "创建数据集",
icon: Database,
prompt: "帮我创建一个新的数据集",
category: "数据管理",
},
{
id: "analyze_quality",
label: "质量分析",
icon: BarChart3,
prompt: "分析我的数据集质量",
category: "数据评估",
},
{
id: "start_synthesis",
label: "数据合成",
icon: Sparkles,
prompt: "启动数据合成任务",
category: "数据合成",
},
{
id: "process_data",
label: "数据清洗",
icon: Settings,
prompt: "对数据集进行预处理",
category: "数据清洗",
},
{
id: "export_report",
label: "导出报告",
icon: Download,
prompt: "导出最新的分析报告",
category: "报告导出",
},
{
id: "check_status",
label: "查看状态",
icon: Clock,
prompt: "查看所有任务的运行状态",
category: "状态查询",
},
];
const mockResponses = {
: {
content:
"我来帮您创建一个新的数据集。请告诉我以下信息:\n\n1. 数据集名称\n2. 数据类型(图像、文本、问答对等)\n3. 预期数据量\n4. 数据来源\n\n您也可以直接说出您的需求,我会为您推荐最适合的配置。",
actions: [
{ type: "create_dataset", label: "开始创建", data: { step: "config" } },
],
},
: {
content:
"正在为您分析数据集质量...\n\n📊 **分析结果概览:**\n- 图像分类数据集:质量分 92/100\n- 问答对数据集:质量分 87/100\n- 多模态数据集:质量分 78/100\n\n🔍 **发现的主要问题:**\n- 23个重复图像\n- 156个格式不正确的问答对\n- 78个图文不匹配项\n\n💡 **改进建议:**\n- 建议进行去重处理\n- 优化问答对格式\n- 重新标注图文匹配项",
actions: [
{
type: "run_analysis",
label: "查看详细报告",
data: { type: "detailed" },
},
],
},
: {
content:
"我可以帮您启动数据合成任务。目前支持以下合成类型:\n\n🖼️ **图像数据合成**\n- 数据增强(旋转、翻转、亮度调整)\n- 风格迁移\n- GAN生成\n\n📝 **文本数据合成**\n- 同义词替换\n- 回译增强\n- GPT生成\n\n❓ **问答对合成**\n- 基于知识库生成\n- 模板变换\n- 多轮对话生成\n\n请告诉我您需要合成什么类型的数据,以及目标数量。",
actions: [
{
type: "start_synthesis",
label: "配置合成任务",
data: { step: "config" },
},
],
},
: {
content:
"正在为您准备最新的分析报告...\n\n📋 **可用报告:**\n- 数据质量评估报告(PDF)\n- 数据分布统计报告(Excel)\n- 模型性能评估报告(PDF)\n- 偏见检测报告(PDF)\n- 综合分析报告(PDF + Excel)\n\n✅ 报告已生成完成,您可以选择下载格式。",
actions: [
{ type: "export_report", label: "下载报告", data: { format: "pdf" } },
],
},
: {
content:
"📊 **当前任务状态概览:**\n\n🟢 **运行中的任务:**\n- 问答对生成任务:65% 完成\n- 图像质量分析:运行中\n- 知识库构建:等待中\n\n✅ **已完成的任务:**\n- 图像分类数据集创建:已完成\n- PDF文档提取:已完成\n- 训练集配比任务:已完成\n\n⚠️ **需要关注的任务:**\n- 多模态数据合成:暂停(需要用户确认参数)\n\n所有任务运行正常,预计2小时内全部完成。",
actions: [],
},
};
export default function AgentPage() {
return <DevelopmentInProgress />;
const navigate = useNavigate();
const [messages, setMessages] = useState<Message[]>([
{
id: "welcome",
type: "assistant",
content:
"👋 您好!我是 Data Agent,您的AI数据助手。\n\n我可以帮您:\n• 创建和管理数据集\n• 分析数据质量\n• 启动处理任务\n• 生成分析报告\n• 回答数据相关问题\n\n请告诉我您需要什么帮助,或者点击下方的快捷操作开始。",
timestamp: new Date(),
},
]);
const [inputValue, setInputValue] = useState("");
const [isTyping, setIsTyping] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<any>(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(() => {
scrollToBottom();
}, [messages]);
const handleSendMessage = async (content: string) => {
if (!content.trim()) return;
const userMessage: Message = {
id: Date.now().toString(),
type: "user",
content: content.trim(),
timestamp: new Date(),
};
setMessages((prev) => [...prev, userMessage]);
setInputValue("");
setIsTyping(true);
// 模拟AI响应
setTimeout(() => {
const response = generateResponse(content);
const assistantMessage: Message = {
id: (Date.now() + 1).toString(),
type: "assistant",
content: response.content,
timestamp: new Date(),
actions: response.actions,
};
setMessages((prev) => [...prev, assistantMessage]);
setIsTyping(false);
}, 1500);
};
const generateResponse = (
input: string
): { content: string; actions?: any[] } => {
const lowerInput = input.toLowerCase();
if (lowerInput.includes("创建") && lowerInput.includes("数据集")) {
return mockResponses["创建数据集"];
} else if (lowerInput.includes("质量") || lowerInput.includes("分析")) {
return mockResponses["质量分析"];
} else if (lowerInput.includes("合成") || lowerInput.includes("生成")) {
return mockResponses["数据合成"];
} else if (lowerInput.includes("导出") || lowerInput.includes("报告")) {
return mockResponses["导出报告"];
} else if (lowerInput.includes("状态") || lowerInput.includes("任务")) {
return mockResponses["查看状态"];
} else if (lowerInput.includes("你好") || lowerInput.includes("帮助")) {
return {
content:
"很高兴为您服务!我是专门为数据集管理设计的AI助手。\n\n我的主要能力包括:\n\n🔧 **数据集操作**\n- 创建、导入、导出数据集\n- 数据预处理和清洗\n- 批量操作和自动化\n\n📊 **智能分析**\n- 数据质量评估\n- 分布统计分析\n- 性能和偏见检测\n\n🤖 **AI增强**\n- 智能数据合成\n- 自动标注建议\n- 知识库构建\n\n请告诉我您的具体需求,我会为您提供最合适的解决方案!",
};
} else {
return {
content: `我理解您想要「${input}」。让我为您分析一下...\n\n基于您的需求,我建议:\n\n1. 首先确认具体的操作目标\n2. 选择合适的数据集和参数\n3. 执行相应的处理流程\n\n您可以提供更多详细信息,或者选择下方的快捷操作来开始。如果需要帮助,请说"帮助"获取完整功能列表。`,
actions: [
{ type: "run_analysis", label: "开始分析", data: { query: input } },
],
};
}
};
const handleQuickAction = (action: QuickAction) => {
handleSendMessage(action.prompt);
};
const handleActionClick = (action: any) => {
const actionMessage: Message = {
id: Date.now().toString(),
type: "assistant",
content: `✅ 正在执行「${action.label}」...\n\n操作已启动,您可以在相应的功能模块中查看详细进度。`,
timestamp: new Date(),
status: "completed",
};
setMessages((prev) => [...prev, actionMessage]);
};
const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage(inputValue);
}
};
const formatMessage = (content: string) => {
return content.split("\n").map((line, index) => (
<div key={index} className="mb-1">
{line || <br />}
</div>
));
};
const onBack = () => {
navigate("/");
};
return (
<div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50">
<div className="h-screen flex flex-col">
{/* Header */}
<div className="bg-gradient-to-r from-purple-500 to-pink-500 text-white p-6">
<div className="max-w-7xl mx-auto">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-white/20 rounded-lg flex items-center justify-center">
<MessageSquare className="w-6 h-6" />
</div>
<div>
<h1 className="text-2xl font-bold">Data Agent</h1>
<p className="text-purple-100">
AI驱动的智能数据助手
</p>
</div>
</div>
<Button
type="default"
icon={<ArrowLeft className="w-4 h-4 mr-2" />}
onClick={onBack}
className="bg-white/10 border-white/20 text-white hover:bg-white/20 hover:border-white/30"
>
</Button>
</div>
</div>
</div>
<div className="flex-1 max-w-7xl mx-auto h-full w-full p-6">
<div className="h-full flex gap-6">
{/* Chat Area */}
<div className="lg:col-span-3 flex flex-1 flex-col h-full">
<div className="flex-1 flex flex-col h-full shadow-lg">
<div className="pb-3 bg-white rounded-t-lg">
<div className="flex items-center justify-between p-4">
<span className="text-lg font-semibold"></span>
<div>
<span className="w-2 h-2 bg-green-500 rounded-full mr-1 inline-block" />
线
</div>
</div>
</div>
<div className="flex-1 flex flex-col justify-between h-full p-0 min-h-0">
{/* Messages */}
<div className="flex-1 overflow-y-auto p-6 bg-white">
<div className="space-y-4 pb-4">
{messages.map((message) => (
<div
key={message.id}
className={`flex gap-3 ${
message.type === "user"
? "justify-end"
: "justify-start"
}`}
>
{message.type === "assistant" && (
<div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center flex-shrink-0">
<Bot className="w-4 h-4 text-white" />
</div>
)}
<div
className={`max-w-[80%] rounded-lg px-4 py-3 ${
message.type === "user"
? "bg-blue-500 text-white"
: "bg-white text-gray-900 shadow-sm border border-gray-100"
}`}
>
<div className="text-sm whitespace-pre-wrap">
{formatMessage(message.content)}
</div>
{message.actions && message.actions.length > 0 && (
<div className="mt-3 space-y-2">
{message.actions.map((action, index) => (
<Button
key={index}
type="default"
size="small"
className="mr-2 mb-2"
onClick={() => handleActionClick(action)}
>
{action.label}
</Button>
))}
</div>
)}
<div className="text-xs opacity-70 mt-2">
{message.timestamp.toLocaleTimeString()}
</div>
</div>
{message.type === "user" && (
<div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0">
<User className="w-4 h-4 text-white" />
</div>
)}
</div>
))}
{isTyping && (
<div className="flex gap-3 justify-start">
<div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
<Bot className="w-4 h-4 text-white" />
</div>
<div className="bg-white rounded-lg px-4 py-3 shadow-sm border border-gray-100">
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce delay-100"></div>
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce delay-200"></div>
</div>
</div>
</div>
)}
</div>
<div ref={messagesEndRef} />
</div>
{/* Input Area */}
<div className="border-t border-gray-200 p-4 bg-white rounded-b-lg">
<div className="flex gap-2">
<Input
ref={inputRef}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyPress}
placeholder="输入您的需求,例如:创建一个图像分类数据集..."
disabled={isTyping}
/>
<Button
type="primary"
onClick={() => handleSendMessage(inputValue)}
disabled={!inputValue.trim() || isTyping}
className="bg-gradient-to-r from-purple-400 to-pink-400 border-none hover:from-purple-500 hover:to-pink-500"
>
<Send className="w-4 h-4" />
</Button>
</div>
</div>
</div>
</div>
</div>
{/* Quick Actions Sidebar */}
<div className="w-72 flex flex-col gap-6">
<Card className="shadow-lg">
<div className="">
<span className="text-lg font-semibold"></span>
<div className="text-sm text-gray-500">
</div>
</div>
<div className="space-y-2 p-4">
{quickActions.map((action) => (
<Button
key={action.id}
type="default"
className="w-full justify-start h-auto p-3 text-left"
onClick={() => handleQuickAction(action)}
>
<action.icon className="w-4 h-4 mr-2 flex-shrink-0" />
<div className="text-left">
<div className="font-medium text-sm">
{action.label}
</div>
</div>
</Button>
))}
</div>
</Card>
<Card className="shadow-lg">
<div className="pb-3">
<span className="text-lg font-semibold"></span>
</div>
<div className="space-y-3 p-4 pt-0">
<div className="flex items-center gap-2 text-sm">
<CheckCircle className="w-4 h-4 text-green-500" />
<span>AI服务正常</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Clock className="w-4 h-4 text-blue-500" />
<span>3</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Database className="w-4 h-4 text-purple-500" />
<span>12</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Zap className="w-4 h-4 text-orange-500" />
<span>响应时间: 0.8s</span>
</div>
</div>
</Card>
<Card className="shadow-lg">
<div className="pb-3">
<span className="text-lg font-semibold">使</span>
</div>
<div className="space-y-2 text-sm text-gray-600 p-4 pt-0">
<div>💡 </div>
<div>🔍 </div>
<div>📊 </div>
<div> 使</div>
</div>
</Card>
<Card className="shadow-lg">
<div className="pt-6 p-4">
<Button
type="default"
className="w-full"
icon={<HomeOutlined />}
onClick={onBack}
>
</Button>
</div>
</Card>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,229 +1,229 @@
import { useEffect, useState } from "react";
import { Card, message } from "antd";
import { Button, Badge, Progress, Checkbox } from "antd";
import {
ArrowLeft,
FileText,
ImageIcon,
Video,
Music,
Save,
SkipForward,
CheckCircle,
Eye,
Settings,
} from "lucide-react";
import { mockTasks } from "@/mock/annotation";
import { Outlet, useNavigate } from "react-router";
export default function AnnotationWorkspace() {
const navigate = useNavigate();
const [task, setTask] = useState(mockTasks[0]);
const [currentFileIndex, setCurrentFileIndex] = useState(0);
const [annotationProgress, setAnnotationProgress] = useState({
completed: task.completedCount,
skipped: task.skippedCount,
total: task.totalCount,
});
const handleSaveAndNext = () => {
setAnnotationProgress((prev) => ({
...prev,
completed: prev.completed + 1,
}));
if (currentFileIndex < task.totalCount - 1) {
setCurrentFileIndex(currentFileIndex + 1);
}
message({
title: "标注已保存",
description: "标注结果已保存,自动跳转到下一个",
});
};
const handleSkipAndNext = () => {
setAnnotationProgress((prev) => ({
...prev,
skipped: prev.skipped + 1,
}));
if (currentFileIndex < task.totalCount - 1) {
setCurrentFileIndex(currentFileIndex + 1);
}
message({
title: "已跳过",
description: "已跳过当前项目,自动跳转到下一个",
});
};
const getDatasetTypeIcon = (type: string) => {
switch (type) {
case "text":
return <FileText className="w-4 h-4 text-blue-500" />;
case "image":
return <ImageIcon className="w-4 h-4 text-green-500" />;
case "video":
return <Video className="w-4 h-4 text-purple-500" />;
case "audio":
return <Music className="w-4 h-4 text-orange-500" />;
default:
return <FileText className="w-4 h-4 text-gray-500" />;
}
};
const currentProgress = Math.round(
((annotationProgress.completed + annotationProgress.skipped) /
annotationProgress.total) *
100
);
return (
<div className="h-screen flex flex-col">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<Button
type="text"
onClick={() => navigate("/data/annotation")}
icon={<ArrowLeft className="w-4 h-4" />}
></Button>
<div className="flex items-center space-x-2">
{getDatasetTypeIcon(task.datasetType)}
<span className="text-xl font-bold">{task.name}</span>
</div>
</div>
<div className="flex items-center space-x-4">
<div className="text-sm text-gray-600">
{currentFileIndex + 1} / {task.totalCount}
</div>
<div className="flex items-center space-x-2 min-w-56">
<span className="text-sm text-gray-600">:</span>
<Progress
percent={currentProgress}
showInfo={false}
className="w-24 h-2"
/>
<span className="text-sm font-medium">{currentProgress}%</span>
</div>
</div>
</div>
{/* Main Content */}
<div className="bg-white border-b border-gray-200 px-6 py-4 flex-1 flex">
{/* Annotation Area */}
<div className="flex-1 flex flex-col">
<Outlet />
</div>
{/* Right Sidebar - Only show for text and image types */}
{(task.datasetType === "text" || task.datasetType === "image") && (
<div className="w-80 border-l border-gray-200 p-4 space-y-4">
{/* Progress Stats */}
<Card>
<div className="space-y-3 pt-4">
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium text-green-500">
{annotationProgress.completed}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium text-red-500">
{annotationProgress.skipped}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium text-gray-600">
{annotationProgress.total -
annotationProgress.completed -
annotationProgress.skipped}
</span>
</div>
<div className="border-t border-gray-200 my-3" />
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium">{currentProgress}%</span>
</div>
</div>
</Card>
{/* Quick Actions */}
<Card>
<div className="pt-4 space-y-2">
<Button
type="primary"
block
onClick={handleSaveAndNext}
className="bg-green-500 border-green-500 hover:bg-green-600 hover:border-green-600"
icon={<CheckCircle className="w-4 h-4 mr-2" />}
>
</Button>
<Button
block
onClick={handleSkipAndNext}
icon={<SkipForward className="w-4 h-4 mr-2" />}
>
</Button>
<Button block icon={<Save className="w-4 h-4 mr-2" />}>
</Button>
<Button block icon={<Eye className="w-4 h-4 mr-2" />}>
</Button>
</div>
</Card>
{/* Navigation */}
<Card>
<div className="pt-4 space-y-2">
<div className="flex items-center space-x-2">
<Button
block
disabled={currentFileIndex === 0}
onClick={() => setCurrentFileIndex(currentFileIndex - 1)}
>
</Button>
<Button
block
disabled={currentFileIndex === task.totalCount - 1}
onClick={() => setCurrentFileIndex(currentFileIndex + 1)}
>
</Button>
</div>
<div className="text-xs text-gray-500">
: {currentFileIndex + 1} / {task.totalCount}
</div>
</div>
</Card>
{/* Settings */}
<Card>
<div className="pt-4 space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm"></span>
<Checkbox defaultChecked />
</div>
<div className="flex items-center justify-between">
<span className="text-sm"></span>
<Checkbox defaultChecked />
</div>
<Button block icon={<Settings className="w-4 h-4 mr-2" />}>
</Button>
</div>
</Card>
</div>
)}
</div>
</div>
);
}
import { useEffect, useState } from "react";
import { Card, message } from "antd";
import { Button, Badge, Progress, Checkbox } from "antd";
import {
ArrowLeft,
FileText,
ImageIcon,
Video,
Music,
Save,
SkipForward,
CheckCircle,
Eye,
Settings,
} from "lucide-react";
import { mockTasks } from "@/mock/annotation";
import { Outlet, useNavigate } from "react-router";
export default function AnnotationWorkspace() {
const navigate = useNavigate();
const [task, setTask] = useState(mockTasks[0]);
const [currentFileIndex, setCurrentFileIndex] = useState(0);
const [annotationProgress, setAnnotationProgress] = useState({
completed: task.completedCount,
skipped: task.skippedCount,
total: task.totalCount,
});
const handleSaveAndNext = () => {
setAnnotationProgress((prev) => ({
...prev,
completed: prev.completed + 1,
}));
if (currentFileIndex < task.totalCount - 1) {
setCurrentFileIndex(currentFileIndex + 1);
}
message({
title: "标注已保存",
description: "标注结果已保存,自动跳转到下一个",
});
};
const handleSkipAndNext = () => {
setAnnotationProgress((prev) => ({
...prev,
skipped: prev.skipped + 1,
}));
if (currentFileIndex < task.totalCount - 1) {
setCurrentFileIndex(currentFileIndex + 1);
}
message({
title: "已跳过",
description: "已跳过当前项目,自动跳转到下一个",
});
};
const getDatasetTypeIcon = (type: string) => {
switch (type) {
case "text":
return <FileText className="w-4 h-4 text-blue-500" />;
case "image":
return <ImageIcon className="w-4 h-4 text-green-500" />;
case "video":
return <Video className="w-4 h-4 text-purple-500" />;
case "audio":
return <Music className="w-4 h-4 text-orange-500" />;
default:
return <FileText className="w-4 h-4 text-gray-500" />;
}
};
const currentProgress = Math.round(
((annotationProgress.completed + annotationProgress.skipped) /
annotationProgress.total) *
100
);
return (
<div className="h-screen flex flex-col">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<Button
type="text"
onClick={() => navigate("/data/annotation")}
icon={<ArrowLeft className="w-4 h-4" />}
></Button>
<div className="flex items-center space-x-2">
{getDatasetTypeIcon(task.datasetType)}
<span className="text-xl font-bold">{task.name}</span>
</div>
</div>
<div className="flex items-center space-x-4">
<div className="text-sm text-gray-600">
{currentFileIndex + 1} / {task.totalCount}
</div>
<div className="flex items-center space-x-2 min-w-56">
<span className="text-sm text-gray-600">:</span>
<Progress
percent={currentProgress}
showInfo={false}
className="w-24 h-2"
/>
<span className="text-sm font-medium">{currentProgress}%</span>
</div>
</div>
</div>
{/* Main Content */}
<div className="bg-white border-b border-gray-200 px-6 py-4 flex-1 flex">
{/* Annotation Area */}
<div className="flex-1 flex flex-col">
<Outlet />
</div>
{/* Right Sidebar - Only show for text and image types */}
{(task.datasetType === "text" || task.datasetType === "image") && (
<div className="w-80 border-l border-gray-200 p-4 space-y-4">
{/* Progress Stats */}
<Card>
<div className="space-y-3 pt-4">
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium text-green-500">
{annotationProgress.completed}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium text-red-500">
{annotationProgress.skipped}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium text-gray-600">
{annotationProgress.total -
annotationProgress.completed -
annotationProgress.skipped}
</span>
</div>
<div className="border-t border-gray-200 my-3" />
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600"></span>
<span className="font-medium">{currentProgress}%</span>
</div>
</div>
</Card>
{/* Quick Actions */}
<Card>
<div className="pt-4 space-y-2">
<Button
type="primary"
block
onClick={handleSaveAndNext}
className="bg-green-500 border-green-500 hover:bg-green-600 hover:border-green-600"
icon={<CheckCircle className="w-4 h-4 mr-2" />}
>
</Button>
<Button
block
onClick={handleSkipAndNext}
icon={<SkipForward className="w-4 h-4 mr-2" />}
>
</Button>
<Button block icon={<Save className="w-4 h-4 mr-2" />}>
</Button>
<Button block icon={<Eye className="w-4 h-4 mr-2" />}>
</Button>
</div>
</Card>
{/* Navigation */}
<Card>
<div className="pt-4 space-y-2">
<div className="flex items-center space-x-2">
<Button
block
disabled={currentFileIndex === 0}
onClick={() => setCurrentFileIndex(currentFileIndex - 1)}
>
</Button>
<Button
block
disabled={currentFileIndex === task.totalCount - 1}
onClick={() => setCurrentFileIndex(currentFileIndex + 1)}
>
</Button>
</div>
<div className="text-xs text-gray-500">
: {currentFileIndex + 1} / {task.totalCount}
</div>
</div>
</Card>
{/* Settings */}
<Card>
<div className="pt-4 space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm"></span>
<Checkbox defaultChecked />
</div>
<div className="flex items-center justify-between">
<span className="text-sm"></span>
<Checkbox defaultChecked />
</div>
<Button block icon={<Settings className="w-4 h-4 mr-2" />}>
</Button>
</div>
</Card>
</div>
)}
</div>
</div>
);
}

View File

@@ -1,457 +1,457 @@
import { useState } from "react";
import { Card, Button, Badge, Input, Checkbox } from "antd";
import {
File,
Search,
CheckCircle,
ThumbsUp,
ThumbsDown,
MessageSquare,
HelpCircle,
} from "lucide-react";
interface QAPair {
id: string;
question: string;
answer: string;
status: "pending" | "approved" | "rejected";
confidence?: number;
}
interface FileData {
id: string;
name: string;
qaPairs: QAPair[];
}
interface TextAnnotationWorkspaceProps {
task: any;
currentFileIndex: number;
onSaveAndNext: () => void;
onSkipAndNext: () => void;
}
// 模拟文件数据
const mockFiles: FileData[] = [
{
id: "1",
name: "document_001.txt",
qaPairs: [
{
id: "1",
question: "什么是人工智能?",
answer:
"人工智能(AI)是计算机科学的一个分支,致力于创建能够执行通常需要人类智能的任务的系统。",
status: "pending",
confidence: 0.85,
},
{
id: "2",
question: "机器学习和深度学习有什么区别?",
answer:
"机器学习是人工智能的一个子集,而深度学习是机器学习的一个子集。深度学习使用神经网络来模拟人脑的工作方式。",
status: "pending",
confidence: 0.92,
},
{
id: "3",
question: "什么是神经网络?",
answer:
"神经网络是一种受生物神经网络启发的计算模型,由相互连接的节点(神经元)组成,能够学习和识别模式。",
status: "pending",
confidence: 0.78,
},
],
},
{
id: "2",
name: "document_002.txt",
qaPairs: [
{
id: "4",
question: "什么是自然语言处理?",
answer:
"自然语言处理(NLP)是人工智能的一个分支,专注于使计算机能够理解、解释和生成人类语言。",
status: "pending",
confidence: 0.88,
},
{
id: "5",
question: "计算机视觉的应用有哪些?",
answer:
"计算机视觉广泛应用于图像识别、人脸识别、自动驾驶、医学影像分析、安防监控等领域。",
status: "pending",
confidence: 0.91,
},
],
},
];
export default function TextAnnotationWorkspace({
onSaveAndNext,
onSkipAndNext,
}: TextAnnotationWorkspaceProps) {
const [selectedFile, setSelectedFile] = useState<FileData | null>(
mockFiles[0]
);
const [searchQuery, setSearchQuery] = useState("");
const [statusFilter, setStatusFilter] = useState("all");
const [selectedQAs, setSelectedQAs] = useState<string[]>([]);
const handleFileSelect = (file: FileData) => {
setSelectedFile(file);
setSelectedQAs([]);
};
const handleQAStatusChange = (
qaId: string,
status: "approved" | "rejected"
) => {
if (selectedFile) {
const updatedFile = {
...selectedFile,
qaPairs: selectedFile.qaPairs.map((qa) =>
qa.id === qaId ? { ...qa, status } : qa
),
};
setSelectedFile(updatedFile);
message({
title: status === "approved" ? "已标记为留用" : "已标记为不留用",
description: `QA对 "${qaId}" 状态已更新`,
});
}
};
const handleBatchApprove = () => {
if (selectedFile && selectedQAs.length > 0) {
const updatedFile = {
...selectedFile,
qaPairs: selectedFile.qaPairs.map((qa) =>
selectedQAs.includes(qa.id)
? { ...qa, status: "approved" as const }
: qa
),
};
setSelectedFile(updatedFile);
setSelectedQAs([]);
message({
title: "批量操作完成",
description: `已将 ${selectedQAs.length} 个QA对标记为留用`,
});
}
};
const handleBatchReject = () => {
if (selectedFile && selectedQAs.length > 0) {
const updatedFile = {
...selectedFile,
qaPairs: selectedFile.qaPairs.map((qa) =>
selectedQAs.includes(qa.id)
? { ...qa, status: "rejected" as const }
: qa
),
};
setSelectedFile(updatedFile);
setSelectedQAs([]);
message({
title: "批量操作完成",
description: `已将 ${selectedQAs.length} 个QA对标记为不留用`,
});
}
};
const handleQASelect = (qaId: string, checked: boolean) => {
if (checked) {
setSelectedQAs([...selectedQAs, qaId]);
} else {
setSelectedQAs(selectedQAs.filter((id) => id !== qaId));
}
};
const handleSelectAll = (checked: boolean) => {
if (checked && selectedFile) {
setSelectedQAs(selectedFile.qaPairs.map((qa) => qa.id));
} else {
setSelectedQAs([]);
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case "approved":
return <Badge className="bg-green-100 text-green-800"></Badge>;
case "rejected":
return <Badge className="bg-red-100 text-red-800"></Badge>;
default:
return <Badge></Badge>;
}
};
const getConfidenceColor = (confidence?: number) => {
if (!confidence) return "text-gray-500";
if (confidence >= 0.8) return "text-green-600";
if (confidence >= 0.6) return "text-yellow-600";
return "text-red-600";
};
const filteredQAs =
selectedFile?.qaPairs.filter((qa) => {
const matchesSearch =
qa.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
qa.answer.toLowerCase().includes(searchQuery.toLowerCase());
const matchesStatus =
statusFilter === "all" || qa.status === statusFilter;
return matchesSearch && matchesStatus;
}) || [];
return (
<div className="flex-1 flex">
{/* File List */}
<div className="w-80 border-r bg-gray-50 p-4">
<div className="space-y-4">
<div>
<h3 className="font-medium mb-2"></h3>
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input placeholder="搜索文件..." className="pl-10" />
</div>
</div>
<div className="h-96">
<div className="space-y-2">
{mockFiles.map((file) => (
<div
key={file.id}
className={`p-3 border rounded-lg cursor-pointer transition-colors ${
selectedFile?.id === file.id
? "border-blue-500 bg-blue-50"
: "border-gray-200 hover:border-gray-300"
}`}
onClick={() => handleFileSelect(file)}
>
<div className="flex items-center space-x-2">
<File className="w-4 h-4 text-gray-400" />
<div className="flex-1">
<div className="font-medium text-sm">{file.name}</div>
<div className="text-xs text-gray-500">
{file.qaPairs.length} QA对
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
{/* QA Annotation Area */}
<div className="flex-1 p-6">
{selectedFile ? (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-bold">{selectedFile.name}</h2>
<p className="text-gray-500">
{selectedFile.qaPairs.length} QA对
</p>
</div>
<div className="flex items-center space-x-2">
<Button
onClick={onSaveAndNext}
className="bg-green-600 hover:bg-green-700"
>
<CheckCircle className="w-4 h-4 mr-2" />
</Button>
<Button onClick={onSkipAndNext}></Button>
</div>
</div>
{/* Filters and Batch Actions */}
<Card>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input
placeholder="搜索QA对..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 w-64"
/>
</div>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-3 py-2 border rounded-md text-sm"
>
<option value="all"></option>
<option value="pending"></option>
<option value="approved"></option>
<option value="rejected"></option>
</select>
</div>
{selectedQAs.length > 0 && (
<div className="flex items-center space-x-2">
<span className="text-sm text-gray-600">
{selectedQAs.length}
</span>
<Button
onClick={handleBatchApprove}
size="sm"
className="bg-green-600 hover:bg-green-700"
>
<ThumbsUp className="w-4 h-4 mr-1" />
</Button>
<Button
onClick={handleBatchReject}
size="sm"
variant="destructive"
>
<ThumbsDown className="w-4 h-4 mr-1" />
</Button>
</div>
)}
</div>
</Card>
{/* QA List */}
<div className="space-y-4">
<div className="flex items-center space-x-2">
<Checkbox
checked={
selectedQAs.length === filteredQAs.length &&
filteredQAs.length > 0
}
onChange={handleSelectAll}
/>
<span className="text-sm font-medium"></span>
</div>
<div className="h-500">
<div className="space-y-4">
{filteredQAs.map((qa) => (
<Card
key={qa.id}
className="hover:shadow-md transition-shadow"
>
<div className="space-y-3">
<div className="flex items-start justify-between">
<div className="flex items-center space-x-2">
<Checkbox
checked={selectedQAs.includes(qa.id)}
onCheckedChange={(checked) =>
handleQASelect(qa.id, checked as boolean)
}
/>
<MessageSquare className="w-4 h-4 text-blue-500" />
<span className="text-sm font-medium">
QA-{qa.id}
</span>
</div>
<div className="flex items-center space-x-2">
{qa.confidence && (
<span
className={`text-xs ${getConfidenceColor(
qa.confidence
)}`}
>
: {(qa.confidence * 100).toFixed(1)}%
</span>
)}
{getStatusBadge(qa.status)}
</div>
</div>
<div className="space-y-2">
<div>
<div className="flex items-center space-x-2 mb-1">
<HelpCircle className="w-4 h-4 text-blue-500" />
<span className="text-sm font-medium text-blue-700">
</span>
</div>
<p className="text-sm bg-blue-50 p-3 rounded">
{qa.question}
</p>
</div>
<div>
<div className="flex items-center space-x-2 mb-1">
<MessageSquare className="w-4 h-4 text-green-500" />
<span className="text-sm font-medium text-green-700">
</span>
</div>
<p className="text-sm bg-green-50 p-3 rounded">
{qa.answer}
</p>
</div>
</div>
<div className="flex items-center justify-end space-x-2">
<Button
onClick={() =>
handleQAStatusChange(qa.id, "approved")
}
size="sm"
variant={
qa.status === "approved" ? "default" : "outline"
}
className={
qa.status === "approved"
? "bg-green-600 hover:bg-green-700"
: ""
}
>
<ThumbsUp className="w-4 h-4 mr-1" />
</Button>
<Button
onClick={() =>
handleQAStatusChange(qa.id, "rejected")
}
size="sm"
variant={
qa.status === "rejected"
? "destructive"
: "outline"
}
>
<ThumbsDown className="w-4 h-4 mr-1" />
</Button>
</div>
</div>
</Card>
))}
</div>
</div>
</div>
</div>
) : (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<File className="w-12 h-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">
</h3>
<p className="text-gray-500">
</p>
</div>
</div>
)}
</div>
</div>
);
}
import { useState } from "react";
import { Card, Button, Badge, Input, Checkbox } from "antd";
import {
File,
Search,
CheckCircle,
ThumbsUp,
ThumbsDown,
MessageSquare,
HelpCircle,
} from "lucide-react";
interface QAPair {
id: string;
question: string;
answer: string;
status: "pending" | "approved" | "rejected";
confidence?: number;
}
interface FileData {
id: string;
name: string;
qaPairs: QAPair[];
}
interface TextAnnotationWorkspaceProps {
task: any;
currentFileIndex: number;
onSaveAndNext: () => void;
onSkipAndNext: () => void;
}
// 模拟文件数据
const mockFiles: FileData[] = [
{
id: "1",
name: "document_001.txt",
qaPairs: [
{
id: "1",
question: "什么是人工智能?",
answer:
"人工智能(AI)是计算机科学的一个分支,致力于创建能够执行通常需要人类智能的任务的系统。",
status: "pending",
confidence: 0.85,
},
{
id: "2",
question: "机器学习和深度学习有什么区别?",
answer:
"机器学习是人工智能的一个子集,而深度学习是机器学习的一个子集。深度学习使用神经网络来模拟人脑的工作方式。",
status: "pending",
confidence: 0.92,
},
{
id: "3",
question: "什么是神经网络?",
answer:
"神经网络是一种受生物神经网络启发的计算模型,由相互连接的节点(神经元)组成,能够学习和识别模式。",
status: "pending",
confidence: 0.78,
},
],
},
{
id: "2",
name: "document_002.txt",
qaPairs: [
{
id: "4",
question: "什么是自然语言处理?",
answer:
"自然语言处理(NLP)是人工智能的一个分支,专注于使计算机能够理解、解释和生成人类语言。",
status: "pending",
confidence: 0.88,
},
{
id: "5",
question: "计算机视觉的应用有哪些?",
answer:
"计算机视觉广泛应用于图像识别、人脸识别、自动驾驶、医学影像分析、安防监控等领域。",
status: "pending",
confidence: 0.91,
},
],
},
];
export default function TextAnnotationWorkspace({
onSaveAndNext,
onSkipAndNext,
}: TextAnnotationWorkspaceProps) {
const [selectedFile, setSelectedFile] = useState<FileData | null>(
mockFiles[0]
);
const [searchQuery, setSearchQuery] = useState("");
const [statusFilter, setStatusFilter] = useState("all");
const [selectedQAs, setSelectedQAs] = useState<string[]>([]);
const handleFileSelect = (file: FileData) => {
setSelectedFile(file);
setSelectedQAs([]);
};
const handleQAStatusChange = (
qaId: string,
status: "approved" | "rejected"
) => {
if (selectedFile) {
const updatedFile = {
...selectedFile,
qaPairs: selectedFile.qaPairs.map((qa) =>
qa.id === qaId ? { ...qa, status } : qa
),
};
setSelectedFile(updatedFile);
message({
title: status === "approved" ? "已标记为留用" : "已标记为不留用",
description: `QA对 "${qaId}" 状态已更新`,
});
}
};
const handleBatchApprove = () => {
if (selectedFile && selectedQAs.length > 0) {
const updatedFile = {
...selectedFile,
qaPairs: selectedFile.qaPairs.map((qa) =>
selectedQAs.includes(qa.id)
? { ...qa, status: "approved" as const }
: qa
),
};
setSelectedFile(updatedFile);
setSelectedQAs([]);
message({
title: "批量操作完成",
description: `已将 ${selectedQAs.length} 个QA对标记为留用`,
});
}
};
const handleBatchReject = () => {
if (selectedFile && selectedQAs.length > 0) {
const updatedFile = {
...selectedFile,
qaPairs: selectedFile.qaPairs.map((qa) =>
selectedQAs.includes(qa.id)
? { ...qa, status: "rejected" as const }
: qa
),
};
setSelectedFile(updatedFile);
setSelectedQAs([]);
message({
title: "批量操作完成",
description: `已将 ${selectedQAs.length} 个QA对标记为不留用`,
});
}
};
const handleQASelect = (qaId: string, checked: boolean) => {
if (checked) {
setSelectedQAs([...selectedQAs, qaId]);
} else {
setSelectedQAs(selectedQAs.filter((id) => id !== qaId));
}
};
const handleSelectAll = (checked: boolean) => {
if (checked && selectedFile) {
setSelectedQAs(selectedFile.qaPairs.map((qa) => qa.id));
} else {
setSelectedQAs([]);
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case "approved":
return <Badge className="bg-green-100 text-green-800"></Badge>;
case "rejected":
return <Badge className="bg-red-100 text-red-800"></Badge>;
default:
return <Badge></Badge>;
}
};
const getConfidenceColor = (confidence?: number) => {
if (!confidence) return "text-gray-500";
if (confidence >= 0.8) return "text-green-600";
if (confidence >= 0.6) return "text-yellow-600";
return "text-red-600";
};
const filteredQAs =
selectedFile?.qaPairs.filter((qa) => {
const matchesSearch =
qa.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
qa.answer.toLowerCase().includes(searchQuery.toLowerCase());
const matchesStatus =
statusFilter === "all" || qa.status === statusFilter;
return matchesSearch && matchesStatus;
}) || [];
return (
<div className="flex-1 flex">
{/* File List */}
<div className="w-80 border-r bg-gray-50 p-4">
<div className="space-y-4">
<div>
<h3 className="font-medium mb-2"></h3>
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input placeholder="搜索文件..." className="pl-10" />
</div>
</div>
<div className="h-96">
<div className="space-y-2">
{mockFiles.map((file) => (
<div
key={file.id}
className={`p-3 border rounded-lg cursor-pointer transition-colors ${
selectedFile?.id === file.id
? "border-blue-500 bg-blue-50"
: "border-gray-200 hover:border-gray-300"
}`}
onClick={() => handleFileSelect(file)}
>
<div className="flex items-center space-x-2">
<File className="w-4 h-4 text-gray-400" />
<div className="flex-1">
<div className="font-medium text-sm">{file.name}</div>
<div className="text-xs text-gray-500">
{file.qaPairs.length} QA对
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
{/* QA Annotation Area */}
<div className="flex-1 p-6">
{selectedFile ? (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-bold">{selectedFile.name}</h2>
<p className="text-gray-500">
{selectedFile.qaPairs.length} QA对
</p>
</div>
<div className="flex items-center space-x-2">
<Button
onClick={onSaveAndNext}
className="bg-green-600 hover:bg-green-700"
>
<CheckCircle className="w-4 h-4 mr-2" />
</Button>
<Button onClick={onSkipAndNext}></Button>
</div>
</div>
{/* Filters and Batch Actions */}
<Card>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input
placeholder="搜索QA对..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 w-64"
/>
</div>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-3 py-2 border rounded-md text-sm"
>
<option value="all"></option>
<option value="pending"></option>
<option value="approved"></option>
<option value="rejected"></option>
</select>
</div>
{selectedQAs.length > 0 && (
<div className="flex items-center space-x-2">
<span className="text-sm text-gray-600">
{selectedQAs.length}
</span>
<Button
onClick={handleBatchApprove}
size="sm"
className="bg-green-600 hover:bg-green-700"
>
<ThumbsUp className="w-4 h-4 mr-1" />
</Button>
<Button
onClick={handleBatchReject}
size="sm"
variant="destructive"
>
<ThumbsDown className="w-4 h-4 mr-1" />
</Button>
</div>
)}
</div>
</Card>
{/* QA List */}
<div className="space-y-4">
<div className="flex items-center space-x-2">
<Checkbox
checked={
selectedQAs.length === filteredQAs.length &&
filteredQAs.length > 0
}
onChange={handleSelectAll}
/>
<span className="text-sm font-medium"></span>
</div>
<div className="h-500">
<div className="space-y-4">
{filteredQAs.map((qa) => (
<Card
key={qa.id}
className="hover:shadow-md transition-shadow"
>
<div className="space-y-3">
<div className="flex items-start justify-between">
<div className="flex items-center space-x-2">
<Checkbox
checked={selectedQAs.includes(qa.id)}
onCheckedChange={(checked) =>
handleQASelect(qa.id, checked as boolean)
}
/>
<MessageSquare className="w-4 h-4 text-blue-500" />
<span className="text-sm font-medium">
QA-{qa.id}
</span>
</div>
<div className="flex items-center space-x-2">
{qa.confidence && (
<span
className={`text-xs ${getConfidenceColor(
qa.confidence
)}`}
>
: {(qa.confidence * 100).toFixed(1)}%
</span>
)}
{getStatusBadge(qa.status)}
</div>
</div>
<div className="space-y-2">
<div>
<div className="flex items-center space-x-2 mb-1">
<HelpCircle className="w-4 h-4 text-blue-500" />
<span className="text-sm font-medium text-blue-700">
</span>
</div>
<p className="text-sm bg-blue-50 p-3 rounded">
{qa.question}
</p>
</div>
<div>
<div className="flex items-center space-x-2 mb-1">
<MessageSquare className="w-4 h-4 text-green-500" />
<span className="text-sm font-medium text-green-700">
</span>
</div>
<p className="text-sm bg-green-50 p-3 rounded">
{qa.answer}
</p>
</div>
</div>
<div className="flex items-center justify-end space-x-2">
<Button
onClick={() =>
handleQAStatusChange(qa.id, "approved")
}
size="sm"
variant={
qa.status === "approved" ? "default" : "outline"
}
className={
qa.status === "approved"
? "bg-green-600 hover:bg-green-700"
: ""
}
>
<ThumbsUp className="w-4 h-4 mr-1" />
</Button>
<Button
onClick={() =>
handleQAStatusChange(qa.id, "rejected")
}
size="sm"
variant={
qa.status === "rejected"
? "destructive"
: "outline"
}
>
<ThumbsDown className="w-4 h-4 mr-1" />
</Button>
</div>
</div>
</Card>
))}
</div>
</div>
</div>
</div>
) : (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<File className="w-12 h-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">
</h3>
<p className="text-gray-500">
</p>
</div>
</div>
)}
</div>
</div>
);
}

View File

@@ -1,346 +1,346 @@
import type React from "react";
import { useEffect, useState } from "react";
import { Card, Button, Input, Select, Divider, Form, message } from "antd";
import TextArea from "antd/es/input/TextArea";
import {
DatabaseOutlined,
CheckOutlined,
PlusOutlined,
} from "@ant-design/icons";
import { mockTemplates } from "@/mock/annotation";
import CustomTemplateDialog from "./components/CustomTemplateDialog";
import { Link, useNavigate } from "react-router";
import { ArrowLeft } from "lucide-react";
import { queryDatasetsUsingGet } from "../../DataManagement/dataset.api";
import {
DatasetType,
type Dataset,
} from "@/pages/DataManagement/dataset.model";
interface Template {
id: string;
name: string;
category: string;
description: string;
type: "text" | "image";
preview?: string;
icon: React.ReactNode;
isCustom?: boolean;
}
const templateCategories = ["Computer Vision", "Natural Language Processing"];
export default function AnnotationTaskCreate() {
const navigate = useNavigate();
const [form] = Form.useForm();
const [showCustomTemplateDialog, setShowCustomTemplateDialog] =
useState(false);
const [selectedCategory, setSelectedCategory] = useState("Computer Vision");
const [searchQuery, setSearchQuery] = useState("");
const [datasetFilter, setDatasetFilter] = useState("all");
const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(
null
);
const [datasets, setDatasets] = useState<Dataset[]>([]);
const [selectedDataset, setSelectedDataset] = useState<Dataset | null>(null);
// 用于Form的受控数据
const [formValues, setFormValues] = useState({
name: "",
description: "",
datasetId: "",
templateId: "",
});
const fetchDatasets = async () => {
const { data } = await queryDatasetsUsingGet();
setDatasets(data.results || []);
};
useEffect(() => {
fetchDatasets();
}, []);
const filteredTemplates = mockTemplates.filter(
(template) => template.category === selectedCategory
);
const handleDatasetSelect = (datasetId: string) => {
const dataset = datasets.find((ds) => ds.id === datasetId) || null;
setSelectedDataset(dataset);
setFormValues((prev) => ({ ...prev, datasetId }));
if (dataset?.type === DatasetType.PRETRAIN_IMAGE) {
setSelectedCategory("Computer Vision");
} else if (dataset?.type === DatasetType.PRETRAIN_TEXT) {
setSelectedCategory("Natural Language Processing");
}
setSelectedTemplate(null);
setFormValues((prev) => ({ ...prev, templateId: "" }));
};
const handleTemplateSelect = (template: Template) => {
setSelectedTemplate(template);
setFormValues((prev) => ({ ...prev, templateId: template.id }));
};
const handleValuesChange = (_, allValues) => {
setFormValues({ ...formValues, ...allValues });
};
const handleSubmit = async () => {
try {
const values = await form.validateFields();
const dataset = datasets.find((ds) => ds.id === values.datasetId);
const template = mockTemplates.find(
(tpl) => tpl.id === values.templateId
);
if (!dataset) {
message.error("请选择数据集");
return;
}
if (!template) {
message.error("请选择标注模板");
return;
}
const taskData = {
name: values.name,
description: values.description,
dataset,
template,
};
// onCreateTask(taskData); // 实际创建逻辑
message.success("标注任务创建成功");
navigate("/data/annotation");
} catch (e) {
// 校验失败
}
};
const handleSaveCustomTemplate = (templateData: any) => {
setSelectedTemplate(templateData);
setFormValues((prev) => ({ ...prev, templateId: templateData.id }));
message.success(`自定义模板 "${templateData.name}" 已创建`);
};
return (
<div className="flex-overflow-auto">
{/* Header */}
<div className="flex items-center mb-2">
<Link to="/data/annotation">
<Button type="text">
<ArrowLeft className="w-4 h-4 mr-1" />
</Button>
</Link>
<h1 className="text-xl font-bold bg-clip-text"></h1>
</div>
<div className="flex-overflow-auto bg-white rounded-lg shadow-sm">
<div className="flex-1 overflow-y-auto p-6">
<Form
form={form}
initialValues={formValues}
onValuesChange={handleValuesChange}
layout="vertical"
>
{/* 基本信息 */}
<h2 className="font-medium text-gray-900 text-lg mb-2"></h2>
<Form.Item
label="任务名称"
name="name"
rules={[{ required: true, message: "请输入任务名称" }]}
>
<Input placeholder="输入任务名称" />
</Form.Item>
<Form.Item
label="任务描述"
name="description"
rules={[{ required: true, message: "请输入任务描述" }]}
>
<TextArea placeholder="详细描述标注任务的要求和目标" rows={3} />
</Form.Item>
<Form.Item
label="选择数据集"
name="datasetId"
rules={[{ required: true, message: "请选择数据集" }]}
>
<Select
optionFilterProp="children"
value={formValues.datasetId}
onChange={handleDatasetSelect}
placeholder="请选择数据集"
size="large"
options={datasets.map((dataset) => ({
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="font-medium text-gray-900">
{dataset?.icon || <DatabaseOutlined className="mr-2" />}
{dataset.name}
</div>
<div className="text-xs text-gray-500">
{dataset?.fileCount} {dataset.size}
</div>
</div>
),
value: dataset.id,
}))}
/>
</Form.Item>
{/* 模板选择 */}
<h2 className="font-medium text-gray-900 text-lg mt-6 mb-2 flex items-center gap-2">
</h2>
<Form.Item
name="templateId"
rules={[{ required: true, message: "请选择标注模板" }]}
>
<div className="flex">
{/* Category Sidebar */}
<div className="w-64 pr-6 border-r border-gray-200">
<div className="space-y-2">
{templateCategories.map((category) => {
const isAvailable =
selectedDataset?.type === "image"
? category === "Computer Vision"
: category === "Natural Language Processing";
return (
<Button
key={category}
type={
selectedCategory === category && isAvailable
? "primary"
: "default"
}
block
disabled={!isAvailable}
onClick={() =>
isAvailable && setSelectedCategory(category)
}
style={{ textAlign: "left", marginBottom: 8 }}
>
{category}
</Button>
);
})}
<Button
type="dashed"
block
icon={<PlusOutlined />}
onClick={() => setShowCustomTemplateDialog(true)}
>
</Button>
</div>
</div>
{/* Template Grid */}
<div className="flex-1 pl-6">
<div className="max-h-96 overflow-auto">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredTemplates.map((template) => (
<div
key={template.id}
className={`border rounded-lg cursor-pointer transition-all hover:shadow-md ${
formValues.templateId === template.id
? "border-blue-500 bg-blue-50"
: "border-gray-200"
}`}
onClick={() => handleTemplateSelect(template)}
>
{template.preview && (
<div className="aspect-video bg-gray-100 rounded-t-lg overflow-hidden">
<img
src={template.preview || "/placeholder.svg"}
alt={template.name}
className="w-full h-full object-cover"
/>
</div>
)}
<div className="p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center space-x-2">
{template.icon}
<span className="font-medium text-sm">
{template.name}
</span>
</div>
</div>
<p className="text-xs text-gray-600">
{template.description}
</p>
</div>
</div>
))}
{/* Custom Template Option */}
<div
className={`border-2 border-dashed rounded-lg cursor-pointer transition-all hover:border-gray-400 ${
selectedTemplate?.isCustom
? "border-blue-500 bg-blue-50"
: "border-gray-300"
}`}
onClick={() => setShowCustomTemplateDialog(true)}
>
<div className="aspect-video bg-gray-50 rounded-t-lg flex items-center justify-center">
<PlusOutlined
style={{ fontSize: 32, color: "#bbb" }}
/>
</div>
<div className="p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center space-x-2">
<PlusOutlined />
<span className="font-medium text-sm">
</span>
</div>
{selectedTemplate?.isCustom && (
<CheckOutlined style={{ color: "#1677ff" }} />
)}
</div>
<p className="text-xs text-gray-600">
</p>
</div>
</div>
</div>
</div>
</div>
</div>
{selectedTemplate && (
<div className="mt-4 p-3 bg-blue-50 rounded-lg">
<div className="flex items-center space-x-2">
<span
className="text-sm font-medium"
style={{ color: "#1677ff" }}
>
</span>
</div>
<p
className="text-sm"
style={{ color: "#1677ff", marginTop: 4 }}
>
{selectedTemplate.name} - {selectedTemplate.description}
</p>
</div>
)}
</Form.Item>
</Form>
</div>
<div className="flex gap-2 justify-end border-t border-gray-200 p-6">
<Button onClick={() => navigate("/data/annotation")}></Button>
<Button type="primary" onClick={handleSubmit}>
</Button>
</div>
</div>
{/* Custom Template Dialog */}
<CustomTemplateDialog
open={showCustomTemplateDialog}
onOpenChange={setShowCustomTemplateDialog}
onSaveTemplate={handleSaveCustomTemplate}
datasetType={selectedDataset?.type || "image"}
/>
</div>
);
}
import type React from "react";
import { useEffect, useState } from "react";
import { Card, Button, Input, Select, Divider, Form, message } from "antd";
import TextArea from "antd/es/input/TextArea";
import {
DatabaseOutlined,
CheckOutlined,
PlusOutlined,
} from "@ant-design/icons";
import { mockTemplates } from "@/mock/annotation";
import CustomTemplateDialog from "./components/CustomTemplateDialog";
import { Link, useNavigate } from "react-router";
import { ArrowLeft } from "lucide-react";
import { queryDatasetsUsingGet } from "../../DataManagement/dataset.api";
import {
DatasetType,
type Dataset,
} from "@/pages/DataManagement/dataset.model";
interface Template {
id: string;
name: string;
category: string;
description: string;
type: "text" | "image";
preview?: string;
icon: React.ReactNode;
isCustom?: boolean;
}
const templateCategories = ["Computer Vision", "Natural Language Processing"];
export default function AnnotationTaskCreate() {
const navigate = useNavigate();
const [form] = Form.useForm();
const [showCustomTemplateDialog, setShowCustomTemplateDialog] =
useState(false);
const [selectedCategory, setSelectedCategory] = useState("Computer Vision");
const [searchQuery, setSearchQuery] = useState("");
const [datasetFilter, setDatasetFilter] = useState("all");
const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(
null
);
const [datasets, setDatasets] = useState<Dataset[]>([]);
const [selectedDataset, setSelectedDataset] = useState<Dataset | null>(null);
// 用于Form的受控数据
const [formValues, setFormValues] = useState({
name: "",
description: "",
datasetId: "",
templateId: "",
});
const fetchDatasets = async () => {
const { data } = await queryDatasetsUsingGet();
setDatasets(data.results || []);
};
useEffect(() => {
fetchDatasets();
}, []);
const filteredTemplates = mockTemplates.filter(
(template) => template.category === selectedCategory
);
const handleDatasetSelect = (datasetId: string) => {
const dataset = datasets.find((ds) => ds.id === datasetId) || null;
setSelectedDataset(dataset);
setFormValues((prev) => ({ ...prev, datasetId }));
if (dataset?.type === DatasetType.PRETRAIN_IMAGE) {
setSelectedCategory("Computer Vision");
} else if (dataset?.type === DatasetType.PRETRAIN_TEXT) {
setSelectedCategory("Natural Language Processing");
}
setSelectedTemplate(null);
setFormValues((prev) => ({ ...prev, templateId: "" }));
};
const handleTemplateSelect = (template: Template) => {
setSelectedTemplate(template);
setFormValues((prev) => ({ ...prev, templateId: template.id }));
};
const handleValuesChange = (_, allValues) => {
setFormValues({ ...formValues, ...allValues });
};
const handleSubmit = async () => {
try {
const values = await form.validateFields();
const dataset = datasets.find((ds) => ds.id === values.datasetId);
const template = mockTemplates.find(
(tpl) => tpl.id === values.templateId
);
if (!dataset) {
message.error("请选择数据集");
return;
}
if (!template) {
message.error("请选择标注模板");
return;
}
const taskData = {
name: values.name,
description: values.description,
dataset,
template,
};
// onCreateTask(taskData); // 实际创建逻辑
message.success("标注任务创建成功");
navigate("/data/annotation");
} catch (e) {
// 校验失败
}
};
const handleSaveCustomTemplate = (templateData: any) => {
setSelectedTemplate(templateData);
setFormValues((prev) => ({ ...prev, templateId: templateData.id }));
message.success(`自定义模板 "${templateData.name}" 已创建`);
};
return (
<div className="flex-overflow-auto">
{/* Header */}
<div className="flex items-center mb-2">
<Link to="/data/annotation">
<Button type="text">
<ArrowLeft className="w-4 h-4 mr-1" />
</Button>
</Link>
<h1 className="text-xl font-bold bg-clip-text"></h1>
</div>
<div className="flex-overflow-auto bg-white rounded-lg shadow-sm">
<div className="flex-1 overflow-y-auto p-6">
<Form
form={form}
initialValues={formValues}
onValuesChange={handleValuesChange}
layout="vertical"
>
{/* 基本信息 */}
<h2 className="font-medium text-gray-900 text-lg mb-2"></h2>
<Form.Item
label="任务名称"
name="name"
rules={[{ required: true, message: "请输入任务名称" }]}
>
<Input placeholder="输入任务名称" />
</Form.Item>
<Form.Item
label="任务描述"
name="description"
rules={[{ required: true, message: "请输入任务描述" }]}
>
<TextArea placeholder="详细描述标注任务的要求和目标" rows={3} />
</Form.Item>
<Form.Item
label="选择数据集"
name="datasetId"
rules={[{ required: true, message: "请选择数据集" }]}
>
<Select
optionFilterProp="children"
value={formValues.datasetId}
onChange={handleDatasetSelect}
placeholder="请选择数据集"
size="large"
options={datasets.map((dataset) => ({
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="font-medium text-gray-900">
{dataset?.icon || <DatabaseOutlined className="mr-2" />}
{dataset.name}
</div>
<div className="text-xs text-gray-500">
{dataset?.fileCount} {dataset.size}
</div>
</div>
),
value: dataset.id,
}))}
/>
</Form.Item>
{/* 模板选择 */}
<h2 className="font-medium text-gray-900 text-lg mt-6 mb-2 flex items-center gap-2">
</h2>
<Form.Item
name="templateId"
rules={[{ required: true, message: "请选择标注模板" }]}
>
<div className="flex">
{/* Category Sidebar */}
<div className="w-64 pr-6 border-r border-gray-200">
<div className="space-y-2">
{templateCategories.map((category) => {
const isAvailable =
selectedDataset?.type === "image"
? category === "Computer Vision"
: category === "Natural Language Processing";
return (
<Button
key={category}
type={
selectedCategory === category && isAvailable
? "primary"
: "default"
}
block
disabled={!isAvailable}
onClick={() =>
isAvailable && setSelectedCategory(category)
}
style={{ textAlign: "left", marginBottom: 8 }}
>
{category}
</Button>
);
})}
<Button
type="dashed"
block
icon={<PlusOutlined />}
onClick={() => setShowCustomTemplateDialog(true)}
>
</Button>
</div>
</div>
{/* Template Grid */}
<div className="flex-1 pl-6">
<div className="max-h-96 overflow-auto">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredTemplates.map((template) => (
<div
key={template.id}
className={`border rounded-lg cursor-pointer transition-all hover:shadow-md ${
formValues.templateId === template.id
? "border-blue-500 bg-blue-50"
: "border-gray-200"
}`}
onClick={() => handleTemplateSelect(template)}
>
{template.preview && (
<div className="aspect-video bg-gray-100 rounded-t-lg overflow-hidden">
<img
src={template.preview || "/placeholder.svg"}
alt={template.name}
className="w-full h-full object-cover"
/>
</div>
)}
<div className="p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center space-x-2">
{template.icon}
<span className="font-medium text-sm">
{template.name}
</span>
</div>
</div>
<p className="text-xs text-gray-600">
{template.description}
</p>
</div>
</div>
))}
{/* Custom Template Option */}
<div
className={`border-2 border-dashed rounded-lg cursor-pointer transition-all hover:border-gray-400 ${
selectedTemplate?.isCustom
? "border-blue-500 bg-blue-50"
: "border-gray-300"
}`}
onClick={() => setShowCustomTemplateDialog(true)}
>
<div className="aspect-video bg-gray-50 rounded-t-lg flex items-center justify-center">
<PlusOutlined
style={{ fontSize: 32, color: "#bbb" }}
/>
</div>
<div className="p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center space-x-2">
<PlusOutlined />
<span className="font-medium text-sm">
</span>
</div>
{selectedTemplate?.isCustom && (
<CheckOutlined style={{ color: "#1677ff" }} />
)}
</div>
<p className="text-xs text-gray-600">
</p>
</div>
</div>
</div>
</div>
</div>
</div>
{selectedTemplate && (
<div className="mt-4 p-3 bg-blue-50 rounded-lg">
<div className="flex items-center space-x-2">
<span
className="text-sm font-medium"
style={{ color: "#1677ff" }}
>
</span>
</div>
<p
className="text-sm"
style={{ color: "#1677ff", marginTop: 4 }}
>
{selectedTemplate.name} - {selectedTemplate.description}
</p>
</div>
)}
</Form.Item>
</Form>
</div>
<div className="flex gap-2 justify-end border-t border-gray-200 p-6">
<Button onClick={() => navigate("/data/annotation")}></Button>
<Button type="primary" onClick={handleSubmit}>
</Button>
</div>
</div>
{/* Custom Template Dialog */}
<CustomTemplateDialog
open={showCustomTemplateDialog}
onOpenChange={setShowCustomTemplateDialog}
onSaveTemplate={handleSaveCustomTemplate}
datasetType={selectedDataset?.type || "image"}
/>
</div>
);
}

View File

@@ -1,192 +1,192 @@
import { queryDatasetsUsingGet } from "@/pages/DataManagement/dataset.api";
import { mapDataset } from "@/pages/DataManagement/dataset.const";
import { Button, Form, Input, Modal, Select, message } from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
import { createAnnotationTaskUsingPost, queryAnnotationTemplatesUsingGet } from "../../annotation.api";
import { Dataset } from "@/pages/DataManagement/dataset.model";
import type { AnnotationTemplate } from "../../annotation.model";
export default function CreateAnnotationTask({
open,
onClose,
onRefresh,
}: {
open: boolean;
onClose: () => void;
onRefresh: () => void;
}) {
const [form] = Form.useForm();
const [datasets, setDatasets] = useState<Dataset[]>([]);
const [templates, setTemplates] = useState<AnnotationTemplate[]>([]);
const [submitting, setSubmitting] = useState(false);
const [nameManuallyEdited, setNameManuallyEdited] = useState(false);
useEffect(() => {
if (!open) return;
const fetchData = async () => {
try {
// Fetch datasets
const { data: datasetData } = await queryDatasetsUsingGet({
page: 0,
pageSize: 1000, // Use camelCase for HTTP params
});
setDatasets(datasetData.content.map(mapDataset) || []);
// Fetch templates
const templateResponse = await queryAnnotationTemplatesUsingGet({
page: 1,
size: 100, // Backend max is 100 (template API uses 'size' not 'pageSize')
});
// The API returns: {code, message, data: {content, total, page, ...}}
if (templateResponse.code === 200 && templateResponse.data) {
const fetchedTemplates = templateResponse.data.content || [];
console.log("Fetched templates:", fetchedTemplates);
setTemplates(fetchedTemplates);
} else {
console.error("Failed to fetch templates:", templateResponse);
setTemplates([]);
}
} catch (error) {
console.error("Error fetching data:", error);
setTemplates([]);
}
};
fetchData();
}, [open]);
// Reset form and manual-edit flag when modal opens
useEffect(() => {
if (open) {
form.resetFields();
setNameManuallyEdited(false);
}
}, [open, form]);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setSubmitting(true);
// Send templateId instead of labelingConfig
const requestData = {
name: values.name,
description: values.description,
datasetId: values.datasetId,
templateId: values.templateId,
};
await createAnnotationTaskUsingPost(requestData);
message?.success?.("创建标注任务成功");
onClose();
onRefresh();
} catch (err: any) {
console.error("Create annotation task failed", err);
const msg = err?.message || err?.data?.message || "创建失败,请稍后重试";
(message as any)?.error?.(msg);
} finally {
setSubmitting(false);
}
};
return (
<Modal
open={open}
onCancel={onClose}
title="创建标注任务"
footer={
<>
<Button onClick={onClose} disabled={submitting}>
</Button>
<Button type="primary" onClick={handleSubmit} loading={submitting}>
</Button>
</>
}
width={800}
>
<Form form={form} layout="vertical">
{/* 数据集 与 标注工程名称 并排显示(数据集在左) */}
<div className="grid grid-cols-2 gap-4">
<Form.Item
label="数据集"
name="datasetId"
rules={[{ required: true, message: "请选择数据集" }]}
>
<Select
placeholder="请选择数据集"
options={datasets.map((dataset) => {
return {
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="flex items-center font-sm text-gray-900">
<span className="mr-2">{(dataset as any).icon}</span>
<span>{dataset.name}</span>
</div>
<div className="text-xs text-gray-500">{dataset.size}</div>
</div>
),
value: dataset.id,
};
})}
onChange={(value) => {
// 如果用户未手动修改名称,则用数据集名称作为默认任务名
if (!nameManuallyEdited) {
const ds = datasets.find((d) => d.id === value);
if (ds) {
form.setFieldsValue({ name: ds.name });
}
}
}}
/>
</Form.Item>
<Form.Item
label="标注工程名称"
name="name"
rules={[{ required: true, message: "请输入任务名称" }]}
>
<Input
placeholder="输入标注工程名称"
onChange={() => setNameManuallyEdited(true)}
/>
</Form.Item>
</div>
{/* 描述变为可选 */}
<Form.Item label="描述" name="description">
<TextArea placeholder="(可选)详细描述标注任务的要求和目标" rows={3} />
</Form.Item>
{/* 标注模板选择 */}
<Form.Item
label="标注模板"
name="templateId"
rules={[{ required: true, message: "请选择标注模板" }]}
>
<Select
placeholder={templates.length === 0 ? "暂无可用模板,请先创建模板" : "请选择标注模板"}
showSearch
optionFilterProp="label"
notFoundContent={templates.length === 0 ? "暂无模板,请前往「标注模板」页面创建" : "未找到匹配的模板"}
options={templates.map((template) => ({
label: template.name,
value: template.id,
// Add description as subtitle
title: template.description,
}))}
optionRender={(option) => (
<div>
<div style={{ fontWeight: 500 }}>{option.label}</div>
{option.data.title && (
<div style={{ fontSize: 12, color: '#999', marginTop: 2 }}>
{option.data.title}
</div>
)}
</div>
)}
/>
</Form.Item>
</Form>
</Modal>
);
}
import { queryDatasetsUsingGet } from "@/pages/DataManagement/dataset.api";
import { mapDataset } from "@/pages/DataManagement/dataset.const";
import { Button, Form, Input, Modal, Select, message } from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
import { createAnnotationTaskUsingPost, queryAnnotationTemplatesUsingGet } from "../../annotation.api";
import { Dataset } from "@/pages/DataManagement/dataset.model";
import type { AnnotationTemplate } from "../../annotation.model";
export default function CreateAnnotationTask({
open,
onClose,
onRefresh,
}: {
open: boolean;
onClose: () => void;
onRefresh: () => void;
}) {
const [form] = Form.useForm();
const [datasets, setDatasets] = useState<Dataset[]>([]);
const [templates, setTemplates] = useState<AnnotationTemplate[]>([]);
const [submitting, setSubmitting] = useState(false);
const [nameManuallyEdited, setNameManuallyEdited] = useState(false);
useEffect(() => {
if (!open) return;
const fetchData = async () => {
try {
// Fetch datasets
const { data: datasetData } = await queryDatasetsUsingGet({
page: 0,
pageSize: 1000, // Use camelCase for HTTP params
});
setDatasets(datasetData.content.map(mapDataset) || []);
// Fetch templates
const templateResponse = await queryAnnotationTemplatesUsingGet({
page: 1,
size: 100, // Backend max is 100 (template API uses 'size' not 'pageSize')
});
// The API returns: {code, message, data: {content, total, page, ...}}
if (templateResponse.code === 200 && templateResponse.data) {
const fetchedTemplates = templateResponse.data.content || [];
console.log("Fetched templates:", fetchedTemplates);
setTemplates(fetchedTemplates);
} else {
console.error("Failed to fetch templates:", templateResponse);
setTemplates([]);
}
} catch (error) {
console.error("Error fetching data:", error);
setTemplates([]);
}
};
fetchData();
}, [open]);
// Reset form and manual-edit flag when modal opens
useEffect(() => {
if (open) {
form.resetFields();
setNameManuallyEdited(false);
}
}, [open, form]);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setSubmitting(true);
// Send templateId instead of labelingConfig
const requestData = {
name: values.name,
description: values.description,
datasetId: values.datasetId,
templateId: values.templateId,
};
await createAnnotationTaskUsingPost(requestData);
message?.success?.("创建标注任务成功");
onClose();
onRefresh();
} catch (err: any) {
console.error("Create annotation task failed", err);
const msg = err?.message || err?.data?.message || "创建失败,请稍后重试";
(message as any)?.error?.(msg);
} finally {
setSubmitting(false);
}
};
return (
<Modal
open={open}
onCancel={onClose}
title="创建标注任务"
footer={
<>
<Button onClick={onClose} disabled={submitting}>
</Button>
<Button type="primary" onClick={handleSubmit} loading={submitting}>
</Button>
</>
}
width={800}
>
<Form form={form} layout="vertical">
{/* 数据集 与 标注工程名称 并排显示(数据集在左) */}
<div className="grid grid-cols-2 gap-4">
<Form.Item
label="数据集"
name="datasetId"
rules={[{ required: true, message: "请选择数据集" }]}
>
<Select
placeholder="请选择数据集"
options={datasets.map((dataset) => {
return {
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="flex items-center font-sm text-gray-900">
<span className="mr-2">{(dataset as any).icon}</span>
<span>{dataset.name}</span>
</div>
<div className="text-xs text-gray-500">{dataset.size}</div>
</div>
),
value: dataset.id,
};
})}
onChange={(value) => {
// 如果用户未手动修改名称,则用数据集名称作为默认任务名
if (!nameManuallyEdited) {
const ds = datasets.find((d) => d.id === value);
if (ds) {
form.setFieldsValue({ name: ds.name });
}
}
}}
/>
</Form.Item>
<Form.Item
label="标注工程名称"
name="name"
rules={[{ required: true, message: "请输入任务名称" }]}
>
<Input
placeholder="输入标注工程名称"
onChange={() => setNameManuallyEdited(true)}
/>
</Form.Item>
</div>
{/* 描述变为可选 */}
<Form.Item label="描述" name="description">
<TextArea placeholder="(可选)详细描述标注任务的要求和目标" rows={3} />
</Form.Item>
{/* 标注模板选择 */}
<Form.Item
label="标注模板"
name="templateId"
rules={[{ required: true, message: "请选择标注模板" }]}
>
<Select
placeholder={templates.length === 0 ? "暂无可用模板,请先创建模板" : "请选择标注模板"}
showSearch
optionFilterProp="label"
notFoundContent={templates.length === 0 ? "暂无模板,请前往「标注模板」页面创建" : "未找到匹配的模板"}
options={templates.map((template) => ({
label: template.name,
value: template.id,
// Add description as subtitle
title: template.description,
}))}
optionRender={(option) => (
<div>
<div style={{ fontWeight: 500 }}>{option.label}</div>
{option.data.title && (
<div style={{ fontSize: 12, color: '#999', marginTop: 2 }}>
{option.data.title}
</div>
)}
</div>
)}
/>
</Form.Item>
</Form>
</Modal>
);
}

View File

@@ -1,195 +1,195 @@
import { queryDatasetsUsingGet } from "@/pages/DataManagement/dataset.api";
import { mapDataset } from "@/pages/DataManagement/dataset.const";
import { Button, Form, Input, Modal, Select, message } from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
import { createAnnotationTaskUsingPost, queryAnnotationTemplatesUsingGet } from "../../annotation.api";
import { Dataset } from "@/pages/DataManagement/dataset.model";
import type { AnnotationTemplate } from "../../annotation.model";
export default function CreateAnnotationTask({
open,
onClose,
onRefresh,
}: {
open: boolean;
onClose: () => void;
onRefresh: () => void;
}) {
const [form] = Form.useForm();
const [datasets, setDatasets] = useState<Dataset[]>([]);
const [templates, setTemplates] = useState<AnnotationTemplate[]>([]);
const [submitting, setSubmitting] = useState(false);
const [nameManuallyEdited, setNameManuallyEdited] = useState(false);
useEffect(() => {
if (!open) return;
const fetchData = async () => {
try {
// Fetch datasets
const { data: datasetData } = await queryDatasetsUsingGet({
page: 0,
pageSize: 1000, // Use camelCase for HTTP params
});
setDatasets(datasetData.content.map(mapDataset) || []);
// Fetch templates
const templateResponse = await queryAnnotationTemplatesUsingGet({
page: 1,
size: 100, // Backend max is 100 (template API uses 'size' not 'pageSize')
});
// The API returns: {code, message, data: {content, total, page, ...}}
if (templateResponse.code === 200 && templateResponse.data) {
const fetchedTemplates = templateResponse.data.content || [];
console.log("Fetched templates:", fetchedTemplates);
setTemplates(fetchedTemplates);
} else {
console.error("Failed to fetch templates:", templateResponse);
setTemplates([]);
}
} catch (error) {
console.error("Error fetching data:", error);
setTemplates([]);
}
};
fetchData();
}, [open]);
// Reset form and manual-edit flag when modal opens
useEffect(() => {
if (open) {
form.resetFields();
setNameManuallyEdited(false);
}
}, [open, form]);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setSubmitting(true);
// Send templateId instead of labelingConfig
const requestData = {
name: values.name,
description: values.description,
datasetId: values.datasetId,
templateId: values.templateId,
};
await createAnnotationTaskUsingPost(requestData);
message?.success?.("创建标注任务成功");
onClose();
onRefresh();
} catch (err: any) {
console.error("Create annotation task failed", err);
const msg = err?.message || err?.data?.message || "创建失败,请稍后重试";
(message as any)?.error?.(msg);
} finally {
setSubmitting(false);
}
};
return (
<Modal
open={open}
onCancel={onClose}
title="创建标注任务"
footer={
<>
<Button onClick={onClose} disabled={submitting}>
</Button>
<Button type="primary" onClick={handleSubmit} loading={submitting}>
</Button>
</>
}
width={800}
>
<Form form={form} layout="vertical">
{/* 数据集 与 标注工程名称 并排显示(数据集在左) */}
<div className="grid grid-cols-2 gap-4">
<Form.Item
label="数据集"
name="datasetId"
rules={[{ required: true, message: "请选择数据集" }]}
>
<Select
placeholder="请选择数据集"
options={datasets.map((dataset) => {
return {
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="flex items-center font-sm text-gray-900">
<span className="mr-2">{(dataset as any).icon}</span>
<span>{dataset.name}</span>
</div>
<div className="text-xs text-gray-500">{dataset.size}</div>
</div>
),
value: dataset.id,
};
})}
onChange={(value) => {
// 如果用户未手动修改名称,则用数据集名称作为默认任务名
if (!nameManuallyEdited) {
const ds = datasets.find((d) => d.id === value);
if (ds) {
form.setFieldsValue({ name: ds.name });
}
}
}}
/>
</Form.Item>
<Form.Item
label="标注工程名称"
name="name"
rules={[{ required: true, message: "请输入任务名称" }]}
>
<Input
placeholder="输入标注工程名称"
onChange={() => setNameManuallyEdited(true)}
/>
</Form.Item>
</div>
{/* 描述变为可选 */}
<Form.Item label="描述" name="description">
<TextArea placeholder="(可选)详细描述标注任务的要求和目标" rows={3} />
</Form.Item>
{/* 标注模板选择 */}
<Form.Item
label="标注模板"
name="templateId"
rules={[{ required: true, message: "请选择标注模板" }]}
>
<Select
placeholder={templates.length === 0 ? "暂无可用模板,请先创建模板" : "请选择标注模板"}
showSearch
optionFilterProp="label"
notFoundContent={templates.length === 0 ? "暂无模板,请前往「标注模板」页面创建" : "未找到匹配的模板"}
options={templates.map((template) => ({
label: template.name,
value: template.id,
// Add description as subtitle
title: template.description,
}))}
optionRender={(option) => (
<div>
<div style={{ fontWeight: 500 }}>{option.label}</div>
{option.data.title && (
<div style={{ fontSize: 12, color: '#999', marginTop: 2 }}>
{option.data.title}
</div>
)}
</div>
)}
/>
</Form.Item>
</Form>
</Modal>
);
}
import { queryDatasetsUsingGet } from "@/pages/DataManagement/dataset.api";
import { mapDataset } from "@/pages/DataManagement/dataset.const";
import { Button, Form, Input, Modal, Select, message } from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
import { createAnnotationTaskUsingPost, queryAnnotationTemplatesUsingGet } from "../../annotation.api";
import { Dataset } from "@/pages/DataManagement/dataset.model";
import type { AnnotationTemplate } from "../../annotation.model";
export default function CreateAnnotationTask({
open,
onClose,
onRefresh,
}: {
open: boolean;
onClose: () => void;
onRefresh: () => void;
}) {
const [form] = Form.useForm();
const [datasets, setDatasets] = useState<Dataset[]>([]);
const [templates, setTemplates] = useState<AnnotationTemplate[]>([]);
const [submitting, setSubmitting] = useState(false);
const [nameManuallyEdited, setNameManuallyEdited] = useState(false);
useEffect(() => {
if (!open) return;
const fetchData = async () => {
try {
// Fetch datasets
const { data: datasetData } = await queryDatasetsUsingGet({
page: 0,
pageSize: 1000, // Use camelCase for HTTP params
});
setDatasets(datasetData.content.map(mapDataset) || []);
// Fetch templates
const templateResponse = await queryAnnotationTemplatesUsingGet({
page: 1,
size: 100, // Backend max is 100 (template API uses 'size' not 'pageSize')
});
// The API returns: {code, message, data: {content, total, page, ...}}
if (templateResponse.code === 200 && templateResponse.data) {
const fetchedTemplates = templateResponse.data.content || [];
console.log("Fetched templates:", fetchedTemplates);
setTemplates(fetchedTemplates);
} else {
console.error("Failed to fetch templates:", templateResponse);
setTemplates([]);
}
} catch (error) {
console.error("Error fetching data:", error);
setTemplates([]);
}
};
fetchData();
}, [open]);
// Reset form and manual-edit flag when modal opens
useEffect(() => {
if (open) {
form.resetFields();
setNameManuallyEdited(false);
}
}, [open, form]);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setSubmitting(true);
// Send templateId instead of labelingConfig
const requestData = {
name: values.name,
description: values.description,
datasetId: values.datasetId,
templateId: values.templateId,
};
await createAnnotationTaskUsingPost(requestData);
message?.success?.("创建标注任务成功");
onClose();
onRefresh();
} catch (err: any) {
console.error("Create annotation task failed", err);
const msg = err?.message || err?.data?.message || "创建失败,请稍后重试";
(message as any)?.error?.(msg);
} finally {
setSubmitting(false);
}
};
return (
<Modal
open={open}
onCancel={onClose}
title="创建标注任务"
footer={
<>
<Button onClick={onClose} disabled={submitting}>
</Button>
<Button type="primary" onClick={handleSubmit} loading={submitting}>
</Button>
</>
}
width={800}
>
<Form form={form} layout="vertical">
{/* 数据集 与 标注工程名称 并排显示(数据集在左) */}
<div className="grid grid-cols-2 gap-4">
<Form.Item
label="数据集"
name="datasetId"
rules={[{ required: true, message: "请选择数据集" }]}
>
<Select
placeholder="请选择数据集"
options={datasets.map((dataset) => {
return {
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="flex items-center font-sm text-gray-900">
<span className="mr-2">{(dataset as any).icon}</span>
<span>{dataset.name}</span>
</div>
<div className="text-xs text-gray-500">{dataset.size}</div>
</div>
),
value: dataset.id,
};
})}
onChange={(value) => {
// 如果用户未手动修改名称,则用数据集名称作为默认任务名
if (!nameManuallyEdited) {
const ds = datasets.find((d) => d.id === value);
if (ds) {
form.setFieldsValue({ name: ds.name });
}
}
}}
/>
</Form.Item>
<Form.Item
label="标注工程名称"
name="name"
rules={[{ required: true, message: "请输入任务名称" }]}
>
<Input
placeholder="输入标注工程名称"
onChange={() => setNameManuallyEdited(true)}
/>
</Form.Item>
</div>
{/* 描述变为可选 */}
<Form.Item label="描述" name="description">
<TextArea placeholder="(可选)详细描述标注任务的要求和目标" rows={3} />
</Form.Item>
{/* 标注模板选择 */}
<Form.Item
label="标注模板"
name="templateId"
rules={[{ required: true, message: "请选择标注模板" }]}
>
<Select
placeholder={templates.length === 0 ? "暂无可用模板,请先创建模板" : "请选择标注模板"}
showSearch
optionFilterProp="label"
notFoundContent={templates.length === 0 ? "暂无模板,请前往「标注模板」页面创建" : "未找到匹配的模板"}
options={templates.map((template) => ({
label: template.name,
value: template.id,
// Add description as subtitle
title: template.description,
}))}
optionRender={(option) => (
<div>
<div style={{ fontWeight: 500 }}>{option.label}</div>
{option.data.title && (
<div style={{ fontSize: 12, color: '#999', marginTop: 2 }}>
{option.data.title}
</div>
)}
</div>
)}
/>
</Form.Item>
</Form>
</Modal>
);
}

View File

@@ -1,225 +1,225 @@
import { useState } from "react";
import {
Modal,
Input,
Card,
message,
Divider,
Radio,
Form,
} from "antd";
import {
AppstoreOutlined,
BorderOutlined,
DotChartOutlined,
EditOutlined,
CheckSquareOutlined,
BarsOutlined,
DeploymentUnitOutlined,
} from "@ant-design/icons";
interface CustomTemplateDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSaveTemplate: (templateData: any) => void;
datasetType: "text" | "image";
}
const { TextArea } = Input;
const defaultImageTemplate = `<View style="display: flex; flex-direction: column; height: 100vh; overflow: auto;">
<View style="display: flex; height: 100%; gap: 10px;">
<View style="height: 100%; width: 85%; display: flex; flex-direction: column; gap: 5px;">
<Header value="WSI图像预览" />
<View style="min-height: 100%;">
<Image name="image" value="$image" zoom="true" />
</View>
</View>
<View style="height: 100%; width: auto;">
<View style="width: auto; display: flex;">
<Text name="case_id_title" toName="image" value="病例号: $case_id" />
</View>
<Text name="part_title" toName="image" value="取材部位: $part" />
<Header value="标注" />
<View style="display: flex; gap: 5px;">
<View>
<Text name="cancer_or_not_title" value="是否有肿瘤" />
<Choices name="cancer_or_not" toName="image">
<Choice value="是" alias="1" />
<Choice value="否" alias="0" />
</Choices>
<Text name="remark_title" value="备注" />
<TextArea name="remark" toName="image" editable="true"/>
</View>
</View>
</View>
</View>
</View>`;
const defaultTextTemplate = `<View style="display: flex; flex-direction: column; height: 100vh;">
<Header value="文本标注界面" />
<View style="display: flex; height: 100%; gap: 10px;">
<View style="flex: 1; padding: 10px;">
<Text name="content" value="$text" />
<Labels name="label" toName="content">
<Label value="正面" background="green" />
<Label value="负面" background="red" />
<Label value="中性" background="gray" />
</Labels>
</View>
<View style="width: 300px; padding: 10px; border-left: 1px solid #ccc;">
<Header value="标注选项" />
<Text name="sentiment_title" value="情感分类" />
<Choices name="sentiment" toName="content">
<Choice value="正面" />
<Choice value="负面" />
<Choice value="中性" />
</Choices>
<Text name="confidence_title" value="置信度" />
<Rating name="confidence" toName="content" maxRating="5" />
<Text name="comment_title" value="备注" />
<TextArea name="comment" toName="content" placeholder="添加备注..." />
</View>
</View>
</View>`;
const annotationTools = [
{ id: "rectangle", label: "矩形框", icon: <BorderOutlined />, type: "image" },
{
id: "polygon",
label: "多边形",
icon: <DeploymentUnitOutlined />,
type: "image",
},
{ id: "circle", label: "圆形", icon: <DotChartOutlined />, type: "image" },
{ id: "point", label: "关键点", icon: <AppstoreOutlined />, type: "image" },
{ id: "text", label: "文本", icon: <EditOutlined />, type: "both" },
{ id: "choices", label: "选择题", icon: <BarsOutlined />, type: "both" },
{
id: "checkbox",
label: "多选框",
icon: <CheckSquareOutlined />,
type: "both",
},
{ id: "textarea", label: "文本域", icon: <BarsOutlined />, type: "both" },
];
export default function CustomTemplateDialog({
open,
onOpenChange,
onSaveTemplate,
datasetType,
}: CustomTemplateDialogProps) {
const [templateName, setTemplateName] = useState("");
const [templateDescription, setTemplateDescription] = useState("");
const [templateCode, setTemplateCode] = useState(
datasetType === "image" ? defaultImageTemplate : defaultTextTemplate
);
const handleSave = () => {
if (!templateName.trim()) {
message.error("请输入模板名称");
return;
}
if (!templateCode.trim()) {
message.error("请输入模板代码");
return;
}
const templateData = {
id: `custom-${Date.now()}`,
name: templateName,
description: templateDescription,
code: templateCode,
type: datasetType,
isCustom: true,
};
onSaveTemplate(templateData);
onOpenChange(false);
message.success("自定义模板已保存");
setTemplateName("");
setTemplateDescription("");
setTemplateCode(
datasetType === "image" ? defaultImageTemplate : defaultTextTemplate
);
};
return (
<Modal
open={open}
onCancel={() => onOpenChange(false)}
okText={"保存模板"}
onOk={handleSave}
width={1200}
className="max-h-[80vh] overflow-auto"
title="自定义标注模板"
>
<div className="flex min-h-[500px]">
<div className="flex-1 pl-6">
<Form layout="vertical">
<Form.Item label="模板名称 *" required>
<Input
placeholder="输入模板名称"
value={templateName}
onChange={(e) => setTemplateName(e.target.value)}
/>
</Form.Item>
<Form.Item label="模板描述">
<Input
placeholder="输入模板描述"
value={templateDescription}
onChange={(e) => setTemplateDescription(e.target.value)}
/>
</Form.Item>
</Form>
<div className="flex gap-6">
<div className="flex-1">
<div className="mb-2 font-medium"></div>
<Card>
<TextArea
rows={20}
value={templateCode}
onChange={(e) => setTemplateCode(e.target.value)}
placeholder="输入模板代码"
/>
</Card>
</div>
<div className="w-96 border-l border-gray-100 pl-6">
<div className="mb-2 font-medium"></div>
<Card
cover={
<img
alt="预览图像"
src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/img_v3_02oi_9b855efe-ce37-4387-a845-d8ef9aaa1a8g.jpg-GhkhlenJlzOQLSDqyBm2iaC6jbv7VA.jpeg"
className="object-cover h-48"
/>
}
>
<div className="mb-2">
<span className="text-gray-500"></span>
<span>undefined</span>
</div>
<div className="mb-2">
<span className="text-gray-500"></span>
<span>undefined</span>
</div>
<Divider />
<div>
<div className="font-medium mb-2"></div>
<div className="mb-2 text-gray-500"></div>
<Radio.Group>
<Radio value="1">[1]</Radio>
<Radio value="0">[2]</Radio>
</Radio.Group>
<div className="mt-4">
<div className="text-gray-500 mb-1"></div>
<TextArea rows={3} placeholder="添加备注..." />
</div>
</div>
</Card>
</div>
</div>
</div>
</div>
</Modal>
);
}
import { useState } from "react";
import {
Modal,
Input,
Card,
message,
Divider,
Radio,
Form,
} from "antd";
import {
AppstoreOutlined,
BorderOutlined,
DotChartOutlined,
EditOutlined,
CheckSquareOutlined,
BarsOutlined,
DeploymentUnitOutlined,
} from "@ant-design/icons";
interface CustomTemplateDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSaveTemplate: (templateData: any) => void;
datasetType: "text" | "image";
}
const { TextArea } = Input;
const defaultImageTemplate = `<View style="display: flex; flex-direction: column; height: 100vh; overflow: auto;">
<View style="display: flex; height: 100%; gap: 10px;">
<View style="height: 100%; width: 85%; display: flex; flex-direction: column; gap: 5px;">
<Header value="WSI图像预览" />
<View style="min-height: 100%;">
<Image name="image" value="$image" zoom="true" />
</View>
</View>
<View style="height: 100%; width: auto;">
<View style="width: auto; display: flex;">
<Text name="case_id_title" toName="image" value="病例号: $case_id" />
</View>
<Text name="part_title" toName="image" value="取材部位: $part" />
<Header value="标注" />
<View style="display: flex; gap: 5px;">
<View>
<Text name="cancer_or_not_title" value="是否有肿瘤" />
<Choices name="cancer_or_not" toName="image">
<Choice value="是" alias="1" />
<Choice value="否" alias="0" />
</Choices>
<Text name="remark_title" value="备注" />
<TextArea name="remark" toName="image" editable="true"/>
</View>
</View>
</View>
</View>
</View>`;
const defaultTextTemplate = `<View style="display: flex; flex-direction: column; height: 100vh;">
<Header value="文本标注界面" />
<View style="display: flex; height: 100%; gap: 10px;">
<View style="flex: 1; padding: 10px;">
<Text name="content" value="$text" />
<Labels name="label" toName="content">
<Label value="正面" background="green" />
<Label value="负面" background="red" />
<Label value="中性" background="gray" />
</Labels>
</View>
<View style="width: 300px; padding: 10px; border-left: 1px solid #ccc;">
<Header value="标注选项" />
<Text name="sentiment_title" value="情感分类" />
<Choices name="sentiment" toName="content">
<Choice value="正面" />
<Choice value="负面" />
<Choice value="中性" />
</Choices>
<Text name="confidence_title" value="置信度" />
<Rating name="confidence" toName="content" maxRating="5" />
<Text name="comment_title" value="备注" />
<TextArea name="comment" toName="content" placeholder="添加备注..." />
</View>
</View>
</View>`;
const annotationTools = [
{ id: "rectangle", label: "矩形框", icon: <BorderOutlined />, type: "image" },
{
id: "polygon",
label: "多边形",
icon: <DeploymentUnitOutlined />,
type: "image",
},
{ id: "circle", label: "圆形", icon: <DotChartOutlined />, type: "image" },
{ id: "point", label: "关键点", icon: <AppstoreOutlined />, type: "image" },
{ id: "text", label: "文本", icon: <EditOutlined />, type: "both" },
{ id: "choices", label: "选择题", icon: <BarsOutlined />, type: "both" },
{
id: "checkbox",
label: "多选框",
icon: <CheckSquareOutlined />,
type: "both",
},
{ id: "textarea", label: "文本域", icon: <BarsOutlined />, type: "both" },
];
export default function CustomTemplateDialog({
open,
onOpenChange,
onSaveTemplate,
datasetType,
}: CustomTemplateDialogProps) {
const [templateName, setTemplateName] = useState("");
const [templateDescription, setTemplateDescription] = useState("");
const [templateCode, setTemplateCode] = useState(
datasetType === "image" ? defaultImageTemplate : defaultTextTemplate
);
const handleSave = () => {
if (!templateName.trim()) {
message.error("请输入模板名称");
return;
}
if (!templateCode.trim()) {
message.error("请输入模板代码");
return;
}
const templateData = {
id: `custom-${Date.now()}`,
name: templateName,
description: templateDescription,
code: templateCode,
type: datasetType,
isCustom: true,
};
onSaveTemplate(templateData);
onOpenChange(false);
message.success("自定义模板已保存");
setTemplateName("");
setTemplateDescription("");
setTemplateCode(
datasetType === "image" ? defaultImageTemplate : defaultTextTemplate
);
};
return (
<Modal
open={open}
onCancel={() => onOpenChange(false)}
okText={"保存模板"}
onOk={handleSave}
width={1200}
className="max-h-[80vh] overflow-auto"
title="自定义标注模板"
>
<div className="flex min-h-[500px]">
<div className="flex-1 pl-6">
<Form layout="vertical">
<Form.Item label="模板名称 *" required>
<Input
placeholder="输入模板名称"
value={templateName}
onChange={(e) => setTemplateName(e.target.value)}
/>
</Form.Item>
<Form.Item label="模板描述">
<Input
placeholder="输入模板描述"
value={templateDescription}
onChange={(e) => setTemplateDescription(e.target.value)}
/>
</Form.Item>
</Form>
<div className="flex gap-6">
<div className="flex-1">
<div className="mb-2 font-medium"></div>
<Card>
<TextArea
rows={20}
value={templateCode}
onChange={(e) => setTemplateCode(e.target.value)}
placeholder="输入模板代码"
/>
</Card>
</div>
<div className="w-96 border-l border-gray-100 pl-6">
<div className="mb-2 font-medium"></div>
<Card
cover={
<img
alt="预览图像"
src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/img_v3_02oi_9b855efe-ce37-4387-a845-d8ef9aaa1a8g.jpg-GhkhlenJlzOQLSDqyBm2iaC6jbv7VA.jpeg"
className="object-cover h-48"
/>
}
>
<div className="mb-2">
<span className="text-gray-500"></span>
<span>undefined</span>
</div>
<div className="mb-2">
<span className="text-gray-500"></span>
<span>undefined</span>
</div>
<Divider />
<div>
<div className="font-medium mb-2"></div>
<div className="mb-2 text-gray-500"></div>
<Radio.Group>
<Radio value="1">[1]</Radio>
<Radio value="0">[2]</Radio>
</Radio.Group>
<div className="mt-4">
<div className="text-gray-500 mb-1"></div>
<TextArea rows={3} placeholder="添加备注..." />
</div>
</div>
</Card>
</div>
</div>
</div>
</div>
</Modal>
);
}

View File

@@ -1,187 +1,187 @@
import { Button, Card, Input, InputNumber, Popconfirm, Select, Switch, Tooltip } from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import { useState, useImperativeHandle, forwardRef } from "react";
type LabelType = "string" | "number" | "enum";
type LabelItem = {
id: string;
name: string;
type: LabelType;
required?: boolean;
// for enum: values; for number: min/max
values?: string[];
min?: number | null;
max?: number | null;
step?: number | null;
};
type LabelingConfigEditorProps = {
initial?: any;
onGenerate: (config: any) => void;
hideFooter?: boolean;
};
export default forwardRef<any, LabelingConfigEditorProps>(function LabelingConfigEditor(
{ initial, onGenerate, hideFooter }: LabelingConfigEditorProps,
ref: any
) {
const [labels, setLabels] = useState<LabelItem[]>(() => {
if (initial && initial.labels && Array.isArray(initial.labels)) {
return initial.labels.map((l: any, idx: number) => ({
id: `${Date.now()}-${idx}`,
name: l.name || "",
type: l.type || "string",
required: !!l.required,
values: l.values || (l.type === "enum" ? [] : undefined),
min: l.min ?? null,
max: l.max ?? null,
}));
}
return [];
});
const addLabel = () => {
setLabels((s) => [
...s,
{ id: `${Date.now()}-${Math.random()}`, name: "", type: "string", required: false, step: null },
]);
};
const updateLabel = (id: string, patch: Partial<LabelItem>) => {
setLabels((s) => s.map((l) => (l.id === id ? { ...l, ...patch } : l)));
};
const removeLabel = (id: string) => {
setLabels((s) => s.filter((l) => l.id !== id));
};
const generate = () => {
// basic validation: label name non-empty
for (const l of labels) {
if (!l.name || l.name.trim() === "") {
// focus not available here, just abort
// Could show a more friendly UI; keep simple for now
// eslint-disable-next-line no-alert
alert("请为所有标签填写名称");
return;
}
if (l.type === "enum") {
if (!l.values || l.values.length === 0) {
alert(`枚举标签 ${l.name} 需要至少一个取值`);
return;
}
}
if (l.type === "number") {
// validate min/max
if (l.min != null && l.max != null && l.min > l.max) {
alert(`数值标签 ${l.name} 的最小值不能大于最大值`);
return;
}
// validate step
if (l.step != null && (!(typeof l.step === "number") || l.step <= 0)) {
alert(`数值标签 ${l.name} 的步长必须为大于 0 的数值`);
return;
}
}
}
const config = {
labels: labels.map((l) => {
const item: any = { name: l.name, type: l.type, required: !!l.required };
if (l.type === "enum") item.values = l.values || [];
if (l.type === "number") {
if (l.min != null) item.min = l.min;
if (l.max != null) item.max = l.max;
}
return item;
}),
};
onGenerate(config);
};
useImperativeHandle(ref, () => ({
addLabel,
generate,
}));
return (
<div>
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
{labels.map((label) => (
<Card size="small" key={label.id} styles={{ body: { padding: 10 } }}>
<div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
<Input
placeholder="标签名称"
value={label.name}
onChange={(e) => updateLabel(label.id, { name: e.target.value })}
style={{ flex: "1 1 160px", minWidth: 120 }}
/>
<Select
value={label.type}
onChange={(v) => updateLabel(label.id, { type: v as LabelType })}
options={[{ label: "文本", value: "string" }, { label: "数值", value: "number" }, { label: "枚举", value: "enum" }]}
style={{ width: 120, flex: "0 0 120px" }}
/>
{label.type === "enum" && (
<Input.TextArea
placeholder="每行一个枚举值,按回车换行"
value={(label.values || []).join("\n")}
onChange={(e) => updateLabel(label.id, { values: e.target.value.split(/\r?\n/).map((s) => s.trim()).filter(Boolean) })}
onKeyDown={(e) => {
// Prevent parent handlers (like Form submit or modal shortcuts) from intercepting Enter
e.stopPropagation();
}}
rows={3}
style={{ flex: "1 1 220px", minWidth: 160, width: "100%", resize: "vertical" }}
/>
)}
{label.type === "number" && (
<div style={{ display: "flex", gap: 8, alignItems: "center", flex: "0 0 auto" }}>
<Tooltip title="最小值">
<InputNumber value={label.min ?? null} onChange={(v) => updateLabel(label.id, { min: v ?? null })} placeholder="min" />
</Tooltip>
<Tooltip title="最大值">
<InputNumber value={label.max ?? null} onChange={(v) => updateLabel(label.id, { max: v ?? null })} placeholder="max" />
</Tooltip>
<Tooltip title="步长 (step)">
<InputNumber value={label.step ?? null} onChange={(v) => updateLabel(label.id, { step: v ?? null })} placeholder="step" min={0} />
</Tooltip>
</div>
)}
<div style={{ display: "flex", alignItems: "center", gap: 8, marginLeft: "auto" }}>
<span style={{ fontSize: 12, color: "rgba(0,0,0,0.65)" }}></span>
<Switch checked={!!label.required} onChange={(v) => updateLabel(label.id, { required: v })} />
<Popconfirm title="确认删除该标签?" onConfirm={() => removeLabel(label.id)}>
<Button type="text" icon={<DeleteOutlined />} />
</Popconfirm>
</div>
</div>
<div style={{ marginTop: 8, color: "rgba(0,0,0,0.45)", fontSize: 12 }}>
{label.type === "string" && <span></span>}
{label.type === "number" && <span> min / max / step</span>}
{label.type === "enum" && <span></span>}
</div>
</Card>
))}
{!hideFooter && (
<div style={{ display: "flex", gap: 8 }}>
<Button icon={<PlusOutlined />} onClick={addLabel}>
</Button>
<Button type="primary" onClick={generate}>
JSON
</Button>
</div>
)}
</div>
</div>
);
}
);
import { Button, Card, Input, InputNumber, Popconfirm, Select, Switch, Tooltip } from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import { useState, useImperativeHandle, forwardRef } from "react";
type LabelType = "string" | "number" | "enum";
type LabelItem = {
id: string;
name: string;
type: LabelType;
required?: boolean;
// for enum: values; for number: min/max
values?: string[];
min?: number | null;
max?: number | null;
step?: number | null;
};
type LabelingConfigEditorProps = {
initial?: any;
onGenerate: (config: any) => void;
hideFooter?: boolean;
};
export default forwardRef<any, LabelingConfigEditorProps>(function LabelingConfigEditor(
{ initial, onGenerate, hideFooter }: LabelingConfigEditorProps,
ref: any
) {
const [labels, setLabels] = useState<LabelItem[]>(() => {
if (initial && initial.labels && Array.isArray(initial.labels)) {
return initial.labels.map((l: any, idx: number) => ({
id: `${Date.now()}-${idx}`,
name: l.name || "",
type: l.type || "string",
required: !!l.required,
values: l.values || (l.type === "enum" ? [] : undefined),
min: l.min ?? null,
max: l.max ?? null,
}));
}
return [];
});
const addLabel = () => {
setLabels((s) => [
...s,
{ id: `${Date.now()}-${Math.random()}`, name: "", type: "string", required: false, step: null },
]);
};
const updateLabel = (id: string, patch: Partial<LabelItem>) => {
setLabels((s) => s.map((l) => (l.id === id ? { ...l, ...patch } : l)));
};
const removeLabel = (id: string) => {
setLabels((s) => s.filter((l) => l.id !== id));
};
const generate = () => {
// basic validation: label name non-empty
for (const l of labels) {
if (!l.name || l.name.trim() === "") {
// focus not available here, just abort
// Could show a more friendly UI; keep simple for now
// eslint-disable-next-line no-alert
alert("请为所有标签填写名称");
return;
}
if (l.type === "enum") {
if (!l.values || l.values.length === 0) {
alert(`枚举标签 ${l.name} 需要至少一个取值`);
return;
}
}
if (l.type === "number") {
// validate min/max
if (l.min != null && l.max != null && l.min > l.max) {
alert(`数值标签 ${l.name} 的最小值不能大于最大值`);
return;
}
// validate step
if (l.step != null && (!(typeof l.step === "number") || l.step <= 0)) {
alert(`数值标签 ${l.name} 的步长必须为大于 0 的数值`);
return;
}
}
}
const config = {
labels: labels.map((l) => {
const item: any = { name: l.name, type: l.type, required: !!l.required };
if (l.type === "enum") item.values = l.values || [];
if (l.type === "number") {
if (l.min != null) item.min = l.min;
if (l.max != null) item.max = l.max;
}
return item;
}),
};
onGenerate(config);
};
useImperativeHandle(ref, () => ({
addLabel,
generate,
}));
return (
<div>
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
{labels.map((label) => (
<Card size="small" key={label.id} styles={{ body: { padding: 10 } }}>
<div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
<Input
placeholder="标签名称"
value={label.name}
onChange={(e) => updateLabel(label.id, { name: e.target.value })}
style={{ flex: "1 1 160px", minWidth: 120 }}
/>
<Select
value={label.type}
onChange={(v) => updateLabel(label.id, { type: v as LabelType })}
options={[{ label: "文本", value: "string" }, { label: "数值", value: "number" }, { label: "枚举", value: "enum" }]}
style={{ width: 120, flex: "0 0 120px" }}
/>
{label.type === "enum" && (
<Input.TextArea
placeholder="每行一个枚举值,按回车换行"
value={(label.values || []).join("\n")}
onChange={(e) => updateLabel(label.id, { values: e.target.value.split(/\r?\n/).map((s) => s.trim()).filter(Boolean) })}
onKeyDown={(e) => {
// Prevent parent handlers (like Form submit or modal shortcuts) from intercepting Enter
e.stopPropagation();
}}
rows={3}
style={{ flex: "1 1 220px", minWidth: 160, width: "100%", resize: "vertical" }}
/>
)}
{label.type === "number" && (
<div style={{ display: "flex", gap: 8, alignItems: "center", flex: "0 0 auto" }}>
<Tooltip title="最小值">
<InputNumber value={label.min ?? null} onChange={(v) => updateLabel(label.id, { min: v ?? null })} placeholder="min" />
</Tooltip>
<Tooltip title="最大值">
<InputNumber value={label.max ?? null} onChange={(v) => updateLabel(label.id, { max: v ?? null })} placeholder="max" />
</Tooltip>
<Tooltip title="步长 (step)">
<InputNumber value={label.step ?? null} onChange={(v) => updateLabel(label.id, { step: v ?? null })} placeholder="step" min={0} />
</Tooltip>
</div>
)}
<div style={{ display: "flex", alignItems: "center", gap: 8, marginLeft: "auto" }}>
<span style={{ fontSize: 12, color: "rgba(0,0,0,0.65)" }}></span>
<Switch checked={!!label.required} onChange={(v) => updateLabel(label.id, { required: v })} />
<Popconfirm title="确认删除该标签?" onConfirm={() => removeLabel(label.id)}>
<Button type="text" icon={<DeleteOutlined />} />
</Popconfirm>
</div>
</div>
<div style={{ marginTop: 8, color: "rgba(0,0,0,0.45)", fontSize: 12 }}>
{label.type === "string" && <span></span>}
{label.type === "number" && <span> min / max / step</span>}
{label.type === "enum" && <span></span>}
</div>
</Card>
))}
{!hideFooter && (
<div style={{ display: "flex", gap: 8 }}>
<Button icon={<PlusOutlined />} onClick={addLabel}>
</Button>
<Button type="primary" onClick={generate}>
JSON
</Button>
</div>
)}
</div>
</div>
);
}
);

View File

@@ -1,398 +1,398 @@
import { useState, useEffect } from "react";
import { Card, Button, Table, message, Modal, Tabs } from "antd";
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
SyncOutlined,
} from "@ant-design/icons";
import { SearchControls } from "@/components/SearchControls";
import CardView from "@/components/CardView";
import type { AnnotationTask } from "../annotation.model";
import useFetchData from "@/hooks/useFetchData";
import {
deleteAnnotationTaskByIdUsingDelete, loginAnnotationUsingGet,
queryAnnotationTasksUsingGet,
syncAnnotationTaskUsingPost,
} from "../annotation.api";
import { mapAnnotationTask } from "../annotation.const";
import CreateAnnotationTask from "../Create/components/CreateAnnotationTaskDialog";
import { ColumnType } from "antd/es/table";
import { TemplateList } from "../Template";
// Note: DevelopmentInProgress intentionally not used here
export default function DataAnnotation() {
// return <DevelopmentInProgress showTime="2025.10.30" />;
const [activeTab, setActiveTab] = useState("tasks");
const [viewMode, setViewMode] = useState<"list" | "card">("list");
const [showCreateDialog, setShowCreateDialog] = useState(false);
const {
loading,
tableData,
pagination,
searchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryAnnotationTasksUsingGet, mapAnnotationTask, 30000, true, [], 0);
const [labelStudioBase, setLabelStudioBase] = useState<string | null>(null);
const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([]);
const [selectedRows, setSelectedRows] = useState<any[]>([]);
// prefetch config on mount so clicking annotate is fast and we know whether base URL exists
// useEffect ensures this runs once
useEffect(() => {
let mounted = true;
(async () => {
try {
const baseUrl = `http://${window.location.hostname}:${parseInt(window.location.port) + 1}`;
if (mounted) setLabelStudioBase(baseUrl);
} catch (e) {
if (mounted) setLabelStudioBase(null);
}
})();
return () => {
mounted = false;
};
}, []);
const handleAnnotate = (task: AnnotationTask) => {
// Open Label Studio project page in a new tab
(async () => {
try {
// prefer using labeling project id already present on the task
// `mapAnnotationTask` normalizes upstream fields into `labelingProjId`/`projId`,
// so prefer those and fall back to the task id if necessary.
let labelingProjId = (task as any).labelingProjId || (task as any).projId || undefined;
// no fallback external mapping lookup; rely on normalized fields from mapAnnotationTask
// use prefetched base if available
const base = labelStudioBase;
// no debug logging in production
if (labelingProjId) {
// only open external Label Studio when we have a configured base url
await loginAnnotationUsingGet(labelingProjId)
if (base) {
const target = `${base}/projects/${labelingProjId}/data`;
window.open(target, "_blank");
} else {
// no external Label Studio URL configured — do not perform internal redirect in this version
message.error("无法跳转到 Label Studio:未配置 Label Studio 基础 URL");
return;
}
} else {
// no labeling project id available — do not attempt internal redirect in this version
message.error("无法跳转到 Label Studio:该映射未绑定标注项目");
return;
}
} catch (error) {
// on error, surface a user-friendly message instead of redirecting
message.error("无法跳转到 Label Studio:发生错误,请检查配置或控制台日志");
return;
}
})();
};
const handleDelete = (task: AnnotationTask) => {
Modal.confirm({
title: `确认删除标注任务「${task.name}」吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "删除",
okType: "danger",
cancelText: "取消",
onOk: async () => {
try {
await deleteAnnotationTaskByIdUsingDelete(task.id);
message.success("映射删除成功");
fetchData();
// clear selection if deleted item was selected
setSelectedRowKeys((keys) => keys.filter((k) => k !== task.id));
setSelectedRows((rows) => rows.filter((r) => r.id !== task.id));
} catch (e) {
console.error(e);
message.error("删除失败,请稍后重试");
}
},
});
};
const handleSync = (task: AnnotationTask, batchSize: number = 50) => {
Modal.confirm({
title: `确认同步标注任务「${task.name}」吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "同步",
cancelText: "取消",
onOk: async () => {
try {
await syncAnnotationTaskUsingPost({ id: task.id, batchSize });
message.success("任务同步请求已发送");
// optional: refresh list/status
fetchData();
// clear selection for the task
setSelectedRowKeys((keys) => keys.filter((k) => k !== task.id));
setSelectedRows((rows) => rows.filter((r) => r.id !== task.id));
} catch (e) {
console.error(e);
message.error("同步失败,请稍后重试");
}
},
});
};
const handleBatchSync = (batchSize: number = 50) => {
if (!selectedRows || selectedRows.length === 0) return;
Modal.confirm({
title: `确认同步所选 ${selectedRows.length} 个标注任务吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "同步",
cancelText: "取消",
onOk: async () => {
try {
await Promise.all(
selectedRows.map((r) => syncAnnotationTaskUsingPost({ id: r.id, batchSize }))
);
message.success("批量同步请求已发送");
fetchData();
setSelectedRowKeys([]);
setSelectedRows([]);
} catch (e) {
console.error(e);
message.error("批量同步失败,请稍后重试");
}
},
});
};
const handleBatchDelete = () => {
if (!selectedRows || selectedRows.length === 0) return;
Modal.confirm({
title: `确认删除所选 ${selectedRows.length} 个标注任务吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "删除",
okType: "danger",
cancelText: "取消",
onOk: async () => {
try {
await Promise.all(
selectedRows.map((r) => deleteAnnotationTaskByIdUsingDelete(r.id))
);
message.success("批量删除已完成");
fetchData();
setSelectedRowKeys([]);
setSelectedRows([]);
} catch (e) {
console.error(e);
message.error("批量删除失败,请稍后重试");
}
},
});
};
const operations = [
{
key: "annotate",
label: "标注",
icon: (
<EditOutlined
className="w-4 h-4 text-green-400"
style={{ color: "#52c41a" }}
/>
),
onClick: handleAnnotate,
},
{
key: "sync",
label: "同步",
icon: <SyncOutlined className="w-4 h-4" style={{ color: "#722ed1" }} />,
onClick: handleSync,
},
{
key: "delete",
label: "删除",
icon: <DeleteOutlined style={{ color: "#f5222d" }} />,
onClick: handleDelete,
},
];
const columns: ColumnType<any>[] = [
{
title: "任务名称",
dataIndex: "name",
key: "name",
fixed: "left" as const,
},
{
title: "任务ID",
dataIndex: "id",
key: "id",
},
{
title: "数据集",
dataIndex: "datasetName",
key: "datasetName",
width: 180,
},
{
title: "创建时间",
dataIndex: "createdAt",
key: "createdAt",
width: 180,
},
{
title: "更新时间",
dataIndex: "updatedAt",
key: "updatedAt",
width: 180,
},
{
title: "操作",
key: "actions",
fixed: "right" as const,
width: 150,
dataIndex: "actions",
render: (_: any, task: any) => (
<div className="flex items-center justify-center space-x-1">
{operations.map((operation) => (
<Button
key={operation.key}
type="text"
icon={operation.icon}
onClick={() => (operation?.onClick as any)?.(task)}
title={operation.label}
/>
))}
</div>
),
},
];
return (
<div className="flex flex-col h-full gap-4">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-bold"></h1>
</div>
{/* Tabs */}
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: "tasks",
label: "标注任务",
children: (
<div className="flex flex-col gap-4">
{/* Search, Filters and Buttons in one row */}
<div className="flex items-center justify-between gap-2">
{/* Left side: Search and view controls */}
<div className="flex items-center gap-2">
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索任务名称、描述"
onFiltersChange={handleFiltersChange}
viewMode={viewMode}
onViewModeChange={setViewMode}
showViewToggle={true}
onReload={fetchData}
/>
</div>
{/* Right side: All action buttons */}
<div className="flex items-center gap-2">
<Button
onClick={() => handleBatchSync(50)}
disabled={selectedRowKeys.length === 0}
>
</Button>
<Button
danger
onClick={handleBatchDelete}
disabled={selectedRowKeys.length === 0}
>
</Button>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => setShowCreateDialog(true)}
>
</Button>
</div>
</div>
{/* Task List/Card */}
{viewMode === "list" ? (
<Card>
<Table
key="id"
rowKey="id"
loading={loading}
columns={columns}
dataSource={tableData}
pagination={pagination}
rowSelection={{
selectedRowKeys,
onChange: (keys, rows) => {
setSelectedRowKeys(keys as (string | number)[]);
setSelectedRows(rows as any[]);
},
}}
scroll={{ x: "max-content", y: "calc(100vh - 24rem)" }}
/>
</Card>
) : (
<CardView
data={tableData}
operations={operations as any}
pagination={pagination}
loading={loading}
/>
)}
<CreateAnnotationTask
open={showCreateDialog}
onClose={() => setShowCreateDialog(false)}
onRefresh={fetchData}
/>
</div>
),
},
{
key: "templates",
label: "标注模板",
children: <TemplateList />,
},
]}
/>
</div>
);
}
import { useState, useEffect } from "react";
import { Card, Button, Table, message, Modal, Tabs } from "antd";
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
SyncOutlined,
} from "@ant-design/icons";
import { SearchControls } from "@/components/SearchControls";
import CardView from "@/components/CardView";
import type { AnnotationTask } from "../annotation.model";
import useFetchData from "@/hooks/useFetchData";
import {
deleteAnnotationTaskByIdUsingDelete, loginAnnotationUsingGet,
queryAnnotationTasksUsingGet,
syncAnnotationTaskUsingPost,
} from "../annotation.api";
import { mapAnnotationTask } from "../annotation.const";
import CreateAnnotationTask from "../Create/components/CreateAnnotationTaskDialog";
import { ColumnType } from "antd/es/table";
import { TemplateList } from "../Template";
// Note: DevelopmentInProgress intentionally not used here
export default function DataAnnotation() {
// return <DevelopmentInProgress showTime="2025.10.30" />;
const [activeTab, setActiveTab] = useState("tasks");
const [viewMode, setViewMode] = useState<"list" | "card">("list");
const [showCreateDialog, setShowCreateDialog] = useState(false);
const {
loading,
tableData,
pagination,
searchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryAnnotationTasksUsingGet, mapAnnotationTask, 30000, true, [], 0);
const [labelStudioBase, setLabelStudioBase] = useState<string | null>(null);
const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([]);
const [selectedRows, setSelectedRows] = useState<any[]>([]);
// prefetch config on mount so clicking annotate is fast and we know whether base URL exists
// useEffect ensures this runs once
useEffect(() => {
let mounted = true;
(async () => {
try {
const baseUrl = `http://${window.location.hostname}:${parseInt(window.location.port) + 1}`;
if (mounted) setLabelStudioBase(baseUrl);
} catch (e) {
if (mounted) setLabelStudioBase(null);
}
})();
return () => {
mounted = false;
};
}, []);
const handleAnnotate = (task: AnnotationTask) => {
// Open Label Studio project page in a new tab
(async () => {
try {
// prefer using labeling project id already present on the task
// `mapAnnotationTask` normalizes upstream fields into `labelingProjId`/`projId`,
// so prefer those and fall back to the task id if necessary.
let labelingProjId = (task as any).labelingProjId || (task as any).projId || undefined;
// no fallback external mapping lookup; rely on normalized fields from mapAnnotationTask
// use prefetched base if available
const base = labelStudioBase;
// no debug logging in production
if (labelingProjId) {
// only open external Label Studio when we have a configured base url
await loginAnnotationUsingGet(labelingProjId)
if (base) {
const target = `${base}/projects/${labelingProjId}/data`;
window.open(target, "_blank");
} else {
// no external Label Studio URL configured — do not perform internal redirect in this version
message.error("无法跳转到 Label Studio:未配置 Label Studio 基础 URL");
return;
}
} else {
// no labeling project id available — do not attempt internal redirect in this version
message.error("无法跳转到 Label Studio:该映射未绑定标注项目");
return;
}
} catch (error) {
// on error, surface a user-friendly message instead of redirecting
message.error("无法跳转到 Label Studio:发生错误,请检查配置或控制台日志");
return;
}
})();
};
const handleDelete = (task: AnnotationTask) => {
Modal.confirm({
title: `确认删除标注任务「${task.name}」吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "删除",
okType: "danger",
cancelText: "取消",
onOk: async () => {
try {
await deleteAnnotationTaskByIdUsingDelete(task.id);
message.success("映射删除成功");
fetchData();
// clear selection if deleted item was selected
setSelectedRowKeys((keys) => keys.filter((k) => k !== task.id));
setSelectedRows((rows) => rows.filter((r) => r.id !== task.id));
} catch (e) {
console.error(e);
message.error("删除失败,请稍后重试");
}
},
});
};
const handleSync = (task: AnnotationTask, batchSize: number = 50) => {
Modal.confirm({
title: `确认同步标注任务「${task.name}」吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "同步",
cancelText: "取消",
onOk: async () => {
try {
await syncAnnotationTaskUsingPost({ id: task.id, batchSize });
message.success("任务同步请求已发送");
// optional: refresh list/status
fetchData();
// clear selection for the task
setSelectedRowKeys((keys) => keys.filter((k) => k !== task.id));
setSelectedRows((rows) => rows.filter((r) => r.id !== task.id));
} catch (e) {
console.error(e);
message.error("同步失败,请稍后重试");
}
},
});
};
const handleBatchSync = (batchSize: number = 50) => {
if (!selectedRows || selectedRows.length === 0) return;
Modal.confirm({
title: `确认同步所选 ${selectedRows.length} 个标注任务吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "同步",
cancelText: "取消",
onOk: async () => {
try {
await Promise.all(
selectedRows.map((r) => syncAnnotationTaskUsingPost({ id: r.id, batchSize }))
);
message.success("批量同步请求已发送");
fetchData();
setSelectedRowKeys([]);
setSelectedRows([]);
} catch (e) {
console.error(e);
message.error("批量同步失败,请稍后重试");
}
},
});
};
const handleBatchDelete = () => {
if (!selectedRows || selectedRows.length === 0) return;
Modal.confirm({
title: `确认删除所选 ${selectedRows.length} 个标注任务吗?`,
content: (
<div>
<div></div>
<div></div>
</div>
),
okText: "删除",
okType: "danger",
cancelText: "取消",
onOk: async () => {
try {
await Promise.all(
selectedRows.map((r) => deleteAnnotationTaskByIdUsingDelete(r.id))
);
message.success("批量删除已完成");
fetchData();
setSelectedRowKeys([]);
setSelectedRows([]);
} catch (e) {
console.error(e);
message.error("批量删除失败,请稍后重试");
}
},
});
};
const operations = [
{
key: "annotate",
label: "标注",
icon: (
<EditOutlined
className="w-4 h-4 text-green-400"
style={{ color: "#52c41a" }}
/>
),
onClick: handleAnnotate,
},
{
key: "sync",
label: "同步",
icon: <SyncOutlined className="w-4 h-4" style={{ color: "#722ed1" }} />,
onClick: handleSync,
},
{
key: "delete",
label: "删除",
icon: <DeleteOutlined style={{ color: "#f5222d" }} />,
onClick: handleDelete,
},
];
const columns: ColumnType<any>[] = [
{
title: "任务名称",
dataIndex: "name",
key: "name",
fixed: "left" as const,
},
{
title: "任务ID",
dataIndex: "id",
key: "id",
},
{
title: "数据集",
dataIndex: "datasetName",
key: "datasetName",
width: 180,
},
{
title: "创建时间",
dataIndex: "createdAt",
key: "createdAt",
width: 180,
},
{
title: "更新时间",
dataIndex: "updatedAt",
key: "updatedAt",
width: 180,
},
{
title: "操作",
key: "actions",
fixed: "right" as const,
width: 150,
dataIndex: "actions",
render: (_: any, task: any) => (
<div className="flex items-center justify-center space-x-1">
{operations.map((operation) => (
<Button
key={operation.key}
type="text"
icon={operation.icon}
onClick={() => (operation?.onClick as any)?.(task)}
title={operation.label}
/>
))}
</div>
),
},
];
return (
<div className="flex flex-col h-full gap-4">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-bold"></h1>
</div>
{/* Tabs */}
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: "tasks",
label: "标注任务",
children: (
<div className="flex flex-col gap-4">
{/* Search, Filters and Buttons in one row */}
<div className="flex items-center justify-between gap-2">
{/* Left side: Search and view controls */}
<div className="flex items-center gap-2">
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索任务名称、描述"
onFiltersChange={handleFiltersChange}
viewMode={viewMode}
onViewModeChange={setViewMode}
showViewToggle={true}
onReload={fetchData}
/>
</div>
{/* Right side: All action buttons */}
<div className="flex items-center gap-2">
<Button
onClick={() => handleBatchSync(50)}
disabled={selectedRowKeys.length === 0}
>
</Button>
<Button
danger
onClick={handleBatchDelete}
disabled={selectedRowKeys.length === 0}
>
</Button>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => setShowCreateDialog(true)}
>
</Button>
</div>
</div>
{/* Task List/Card */}
{viewMode === "list" ? (
<Card>
<Table
key="id"
rowKey="id"
loading={loading}
columns={columns}
dataSource={tableData}
pagination={pagination}
rowSelection={{
selectedRowKeys,
onChange: (keys, rows) => {
setSelectedRowKeys(keys as (string | number)[]);
setSelectedRows(rows as any[]);
},
}}
scroll={{ x: "max-content", y: "calc(100vh - 24rem)" }}
/>
</Card>
) : (
<CardView
data={tableData}
operations={operations as any}
pagination={pagination}
loading={loading}
/>
)}
<CreateAnnotationTask
open={showCreateDialog}
onClose={() => setShowCreateDialog(false)}
onRefresh={fetchData}
/>
</div>
),
},
{
key: "templates",
label: "标注模板",
children: <TemplateList />,
},
]}
/>
</div>
);
}

View File

@@ -1,155 +1,155 @@
import React from "react";
import { Modal, Descriptions, Tag, Space, Divider, Card, Typography } from "antd";
import type { AnnotationTemplate } from "../annotation.model";
const { Text, Paragraph } = Typography;
interface TemplateDetailProps {
visible: boolean;
template?: AnnotationTemplate;
onClose: () => void;
}
const TemplateDetail: React.FC<TemplateDetailProps> = ({
visible,
template,
onClose,
}) => {
if (!template) return null;
return (
<Modal
title="模板详情"
open={visible}
onCancel={onClose}
footer={null}
width={800}
>
<Descriptions bordered column={2}>
<Descriptions.Item label="名称" span={2}>
{template.name}
</Descriptions.Item>
<Descriptions.Item label="描述" span={2}>
{template.description || "-"}
</Descriptions.Item>
<Descriptions.Item label="数据类型">
<Tag color="cyan">{template.dataType}</Tag>
</Descriptions.Item>
<Descriptions.Item label="标注类型">
<Tag color="geekblue">{template.labelingType}</Tag>
</Descriptions.Item>
<Descriptions.Item label="分类">
<Tag color="blue">{template.category}</Tag>
</Descriptions.Item>
<Descriptions.Item label="样式">
{template.style}
</Descriptions.Item>
<Descriptions.Item label="类型">
<Tag color={template.builtIn ? "gold" : "default"}>
{template.builtIn ? "系统内置" : "自定义"}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="版本">
{template.version}
</Descriptions.Item>
<Descriptions.Item label="创建时间" span={2}>
{new Date(template.createdAt).toLocaleString()}
</Descriptions.Item>
{template.updatedAt && (
<Descriptions.Item label="更新时间" span={2}>
{new Date(template.updatedAt).toLocaleString()}
</Descriptions.Item>
)}
</Descriptions>
<Divider></Divider>
<Card title="数据对象" size="small" style={{ marginBottom: 16 }}>
<Space direction="vertical" style={{ width: "100%" }}>
{template.configuration.objects.map((obj, index) => (
<Card key={index} size="small" type="inner">
<Space>
<Text strong></Text>
<Tag>{obj.name}</Tag>
<Text strong></Text>
<Tag color="blue">{obj.type}</Tag>
<Text strong></Text>
<Tag color="green">{obj.value}</Tag>
</Space>
</Card>
))}
</Space>
</Card>
<Card title="标注控件" size="small" style={{ marginBottom: 16 }}>
<Space direction="vertical" style={{ width: "100%" }} size="middle">
{template.configuration.labels.map((label, index) => (
<Card key={index} size="small" type="inner" title={`控件 ${index + 1}`}>
<Space direction="vertical" style={{ width: "100%" }}>
<div>
<Text strong></Text>
<Tag>{label.fromName}</Tag>
<Text strong style={{ marginLeft: 16 }}></Text>
<Tag>{label.toName}</Tag>
<Text strong style={{ marginLeft: 16 }}></Text>
<Tag color="purple">{label.type}</Tag>
{label.required && <Tag color="red"></Tag>}
</div>
{label.description && (
<div>
<Text strong></Text>
<Text type="secondary">{label.description}</Text>
</div>
)}
{label.options && label.options.length > 0 && (
<div>
<Text strong></Text>
<div style={{ marginTop: 4 }}>
{label.options.map((opt, i) => (
<Tag key={i} color="cyan">{opt}</Tag>
))}
</div>
</div>
)}
{label.labels && label.labels.length > 0 && (
<div>
<Text strong></Text>
<div style={{ marginTop: 4 }}>
{label.labels.map((lbl, i) => (
<Tag key={i} color="geekblue">{lbl}</Tag>
))}
</div>
</div>
)}
</Space>
</Card>
))}
</Space>
</Card>
{template.labelConfig && (
<Card title="Label Studio XML 配置" size="small">
<Paragraph>
<pre style={{
background: "#f5f5f5",
padding: 12,
borderRadius: 4,
overflow: "auto",
maxHeight: 300
}}>
{template.labelConfig}
</pre>
</Paragraph>
</Card>
)}
</Modal>
);
};
export default TemplateDetail;
import React from "react";
import { Modal, Descriptions, Tag, Space, Divider, Card, Typography } from "antd";
import type { AnnotationTemplate } from "../annotation.model";
const { Text, Paragraph } = Typography;
interface TemplateDetailProps {
visible: boolean;
template?: AnnotationTemplate;
onClose: () => void;
}
const TemplateDetail: React.FC<TemplateDetailProps> = ({
visible,
template,
onClose,
}) => {
if (!template) return null;
return (
<Modal
title="模板详情"
open={visible}
onCancel={onClose}
footer={null}
width={800}
>
<Descriptions bordered column={2}>
<Descriptions.Item label="名称" span={2}>
{template.name}
</Descriptions.Item>
<Descriptions.Item label="描述" span={2}>
{template.description || "-"}
</Descriptions.Item>
<Descriptions.Item label="数据类型">
<Tag color="cyan">{template.dataType}</Tag>
</Descriptions.Item>
<Descriptions.Item label="标注类型">
<Tag color="geekblue">{template.labelingType}</Tag>
</Descriptions.Item>
<Descriptions.Item label="分类">
<Tag color="blue">{template.category}</Tag>
</Descriptions.Item>
<Descriptions.Item label="样式">
{template.style}
</Descriptions.Item>
<Descriptions.Item label="类型">
<Tag color={template.builtIn ? "gold" : "default"}>
{template.builtIn ? "系统内置" : "自定义"}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="版本">
{template.version}
</Descriptions.Item>
<Descriptions.Item label="创建时间" span={2}>
{new Date(template.createdAt).toLocaleString()}
</Descriptions.Item>
{template.updatedAt && (
<Descriptions.Item label="更新时间" span={2}>
{new Date(template.updatedAt).toLocaleString()}
</Descriptions.Item>
)}
</Descriptions>
<Divider></Divider>
<Card title="数据对象" size="small" style={{ marginBottom: 16 }}>
<Space direction="vertical" style={{ width: "100%" }}>
{template.configuration.objects.map((obj, index) => (
<Card key={index} size="small" type="inner">
<Space>
<Text strong></Text>
<Tag>{obj.name}</Tag>
<Text strong></Text>
<Tag color="blue">{obj.type}</Tag>
<Text strong></Text>
<Tag color="green">{obj.value}</Tag>
</Space>
</Card>
))}
</Space>
</Card>
<Card title="标注控件" size="small" style={{ marginBottom: 16 }}>
<Space direction="vertical" style={{ width: "100%" }} size="middle">
{template.configuration.labels.map((label, index) => (
<Card key={index} size="small" type="inner" title={`控件 ${index + 1}`}>
<Space direction="vertical" style={{ width: "100%" }}>
<div>
<Text strong></Text>
<Tag>{label.fromName}</Tag>
<Text strong style={{ marginLeft: 16 }}></Text>
<Tag>{label.toName}</Tag>
<Text strong style={{ marginLeft: 16 }}></Text>
<Tag color="purple">{label.type}</Tag>
{label.required && <Tag color="red"></Tag>}
</div>
{label.description && (
<div>
<Text strong></Text>
<Text type="secondary">{label.description}</Text>
</div>
)}
{label.options && label.options.length > 0 && (
<div>
<Text strong></Text>
<div style={{ marginTop: 4 }}>
{label.options.map((opt, i) => (
<Tag key={i} color="cyan">{opt}</Tag>
))}
</div>
</div>
)}
{label.labels && label.labels.length > 0 && (
<div>
<Text strong></Text>
<div style={{ marginTop: 4 }}>
{label.labels.map((lbl, i) => (
<Tag key={i} color="geekblue">{lbl}</Tag>
))}
</div>
</div>
)}
</Space>
</Card>
))}
</Space>
</Card>
{template.labelConfig && (
<Card title="Label Studio XML 配置" size="small">
<Paragraph>
<pre style={{
background: "#f5f5f5",
padding: 12,
borderRadius: 4,
overflow: "auto",
maxHeight: 300
}}>
{template.labelConfig}
</pre>
</Paragraph>
</Card>
)}
</Modal>
);
};
export default TemplateDetail;

View File

@@ -1,427 +1,427 @@
import React, { useState, useEffect } from "react";
import {
Modal,
Form,
Input,
Select,
Button,
Space,
message,
Divider,
Card,
Checkbox,
} from "antd";
import { PlusOutlined, MinusCircleOutlined } from "@ant-design/icons";
import {
createAnnotationTemplateUsingPost,
updateAnnotationTemplateByIdUsingPut,
} from "../annotation.api";
import type { AnnotationTemplate } from "../annotation.model";
import TagSelector from "./components/TagSelector";
const { TextArea } = Input;
const { Option } = Select;
interface TemplateFormProps {
visible: boolean;
mode: "create" | "edit";
template?: AnnotationTemplate;
onSuccess: () => void;
onCancel: () => void;
}
const TemplateForm: React.FC<TemplateFormProps> = ({
visible,
mode,
template,
onSuccess,
onCancel,
}) => {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
useEffect(() => {
if (visible && template && mode === "edit") {
form.setFieldsValue({
name: template.name,
description: template.description,
dataType: template.dataType,
labelingType: template.labelingType,
style: template.style,
category: template.category,
labels: template.configuration.labels,
objects: template.configuration.objects,
});
} else if (visible && mode === "create") {
form.resetFields();
// Set default values
form.setFieldsValue({
style: "horizontal",
category: "custom",
labels: [],
objects: [{ name: "image", type: "Image", value: "$image" }],
});
}
}, [visible, template, mode, form]);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setLoading(true);
console.log("Form values:", values);
const requestData = {
name: values.name,
description: values.description,
dataType: values.dataType,
labelingType: values.labelingType,
style: values.style,
category: values.category,
configuration: {
labels: values.labels,
objects: values.objects,
},
};
console.log("Request data:", requestData);
let response;
if (mode === "create") {
response = await createAnnotationTemplateUsingPost(requestData);
} else {
response = await updateAnnotationTemplateByIdUsingPut(template!.id, requestData);
}
if (response.code === 200) {
message.success(`模板${mode === "create" ? "创建" : "更新"}成功`);
form.resetFields();
onSuccess();
} else {
message.error(response.message || `模板${mode === "create" ? "创建" : "更新"}失败`);
}
} catch (error: any) {
if (error.errorFields) {
message.error("请填写所有必填字段");
} else {
message.error(`模板${mode === "create" ? "创建" : "更新"}失败`);
console.error(error);
}
} finally {
setLoading(false);
}
};
const needsOptions = (type: string) => {
return ["Choices", "RectangleLabels", "PolygonLabels", "Labels"].includes(type);
};
return (
<Modal
title={mode === "create" ? "创建模板" : "编辑模板"}
open={visible}
onCancel={onCancel}
onOk={handleSubmit}
confirmLoading={loading}
width={900}
destroyOnClose
>
<Form
form={form}
layout="vertical"
style={{ maxHeight: "70vh", overflowY: "auto", paddingRight: 8 }}
>
<Form.Item
label="模板名称"
name="name"
rules={[{ required: true, message: "请输入模板名称" }]}
>
<Input placeholder="例如:产品质量分类" maxLength={100} />
</Form.Item>
<Form.Item label="描述" name="description">
<TextArea
placeholder="描述此模板的用途"
rows={2}
maxLength={500}
/>
</Form.Item>
<Space style={{ width: "100%" }} size="large">
<Form.Item
label="数据类型"
name="dataType"
rules={[{ required: true, message: "请选择数据类型" }]}
style={{ width: 200 }}
>
<Select placeholder="选择数据类型">
<Option value="image"></Option>
<Option value="text"></Option>
<Option value="audio"></Option>
<Option value="video"></Option>
</Select>
</Form.Item>
<Form.Item
label="标注类型"
name="labelingType"
rules={[{ required: true, message: "请选择标注类型" }]}
style={{ width: 220 }}
>
<Select placeholder="选择标注类型">
<Option value="classification"></Option>
<Option value="object-detection"></Option>
<Option value="segmentation"></Option>
<Option value="ner"></Option>
<Option value="multi-stage"></Option>
</Select>
</Form.Item>
<Form.Item
label="样式"
name="style"
style={{ width: 150 }}
>
<Select>
<Option value="horizontal"></Option>
<Option value="vertical"></Option>
</Select>
</Form.Item>
<Form.Item
label="分类"
name="category"
style={{ width: 180 }}
>
<Select>
<Option value="computer-vision"></Option>
<Option value="nlp"></Option>
<Option value="audio"></Option>
<Option value="quality-control"></Option>
<Option value="custom"></Option>
</Select>
</Form.Item>
</Space>
<Divider></Divider>
<Form.List name="objects">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Card key={field.key} size="small" style={{ marginBottom: 8 }}>
<Space align="start" style={{ width: "100%" }}>
<Form.Item
{...field}
label="名称"
name={[field.name, "name"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0, width: 150 }}
>
<Input placeholder="例如:image" />
</Form.Item>
<Form.Item
{...field}
label="类型"
name={[field.name, "type"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0, width: 150 }}
>
<TagSelector type="object" />
</Form.Item>
<Form.Item
{...field}
label="值"
name={[field.name, "value"]}
rules={[
{ required: true, message: "必填" },
{ pattern: /^\$/, message: "必须以 $ 开头" },
]}
style={{ marginBottom: 0, width: 150 }}
>
<Input placeholder="$image" />
</Form.Item>
{fields.length > 1 && (
<MinusCircleOutlined
style={{ marginTop: 30, color: "red" }}
onClick={() => remove(field.name)}
/>
)}
</Space>
</Card>
))}
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
</Button>
</>
)}
</Form.List>
<Divider></Divider>
<Form.List name="labels">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Card
key={field.key}
size="small"
style={{ marginBottom: 12 }}
title={
<Space>
<span> {fields.indexOf(field) + 1}</span>
<Form.Item noStyle shouldUpdate>
{() => {
const controlType = form.getFieldValue(["labels", field.name, "type"]);
const fromName = form.getFieldValue(["labels", field.name, "fromName"]);
if (controlType || fromName) {
return (
<span style={{ fontSize: 12, fontWeight: 'normal', color: '#999' }}>
({fromName || '未命名'} - {controlType || '未设置类型'})
</span>
);
}
return null;
}}
</Form.Item>
</Space>
}
extra={
<MinusCircleOutlined
style={{ color: "red" }}
onClick={() => remove(field.name)}
/>
}
>
<Space direction="vertical" style={{ width: "100%" }} size="middle">
{/* Row 1: 控件名称, 标注目标对象, 控件类型 */}
<div style={{ display: 'grid', gridTemplateColumns: '180px 220px 1fr auto', gap: 12, alignItems: 'flex-end' }}>
<Form.Item
{...field}
label="来源名称"
name={[field.name, "fromName"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0 }}
tooltip="此控件的唯一标识符"
>
<Input placeholder="例如:choice" />
</Form.Item>
<Form.Item
{...field}
label="标注目标对象"
name={[field.name, "toName"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0 }}
tooltip="选择此控件将标注哪个数据对象"
dependencies={['objects']}
>
<Select placeholder="选择数据对象">
{(form.getFieldValue("objects") || []).map((obj: any, idx: number) => (
<Option key={idx} value={obj?.name || ''}>
{obj?.name || `对象 ${idx + 1}`} ({obj?.type || '未知类型'})
</Option>
))}
</Select>
</Form.Item>
<Form.Item
{...field}
label="控件类型"
name={[field.name, "type"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0 }}
>
<TagSelector type="control" />
</Form.Item>
<Form.Item
{...field}
label=" "
name={[field.name, "required"]}
valuePropName="checked"
style={{ marginBottom: 0 }}
>
<Checkbox></Checkbox>
</Form.Item>
</div>
{/* Row 2: 取值范围定义(添加选项) - Conditionally rendered based on type */}
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) => {
const prevType = prevValues.labels?.[field.name]?.type;
const currType = currentValues.labels?.[field.name]?.type;
return prevType !== currType;
}}
>
{({ getFieldValue }) => {
const controlType = getFieldValue(["labels", field.name, "type"]);
const fieldName = controlType === "Choices" ? "options" : "labels";
if (needsOptions(controlType)) {
return (
<Form.Item
{...field}
label={controlType === "Choices" ? "选项" : "标签"}
name={[field.name, fieldName]}
rules={[{ required: true, message: "至少需要一个选项" }]}
style={{ marginBottom: 0 }}
>
<Select
mode="tags"
open={false}
placeholder={
controlType === "Choices"
? "输入选项内容,按回车添加。例如:是、否、不确定"
: "输入标签名称,按回车添加。例如:人物、车辆、建筑物"
}
style={{ width: "100%" }}
/>
</Form.Item>
);
}
return null;
}}
</Form.Item>
{/* Row 3: 描述 */}
<Form.Item
{...field}
label="描述"
name={[field.name, "description"]}
style={{ marginBottom: 0 }}
tooltip="向标注人员显示的帮助信息"
>
<Input placeholder="为标注人员提供此控件的使用说明" maxLength={200} />
</Form.Item>
</Space>
</Card>
))}
<Button
type="dashed"
onClick={() =>
add({
fromName: "",
toName: "",
type: "Choices",
required: false,
})
}
block
icon={<PlusOutlined />}
>
</Button>
</>
)}
</Form.List>
</Form>
</Modal>
);
};
export default TemplateForm;
import React, { useState, useEffect } from "react";
import {
Modal,
Form,
Input,
Select,
Button,
Space,
message,
Divider,
Card,
Checkbox,
} from "antd";
import { PlusOutlined, MinusCircleOutlined } from "@ant-design/icons";
import {
createAnnotationTemplateUsingPost,
updateAnnotationTemplateByIdUsingPut,
} from "../annotation.api";
import type { AnnotationTemplate } from "../annotation.model";
import TagSelector from "./components/TagSelector";
const { TextArea } = Input;
const { Option } = Select;
interface TemplateFormProps {
visible: boolean;
mode: "create" | "edit";
template?: AnnotationTemplate;
onSuccess: () => void;
onCancel: () => void;
}
const TemplateForm: React.FC<TemplateFormProps> = ({
visible,
mode,
template,
onSuccess,
onCancel,
}) => {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
useEffect(() => {
if (visible && template && mode === "edit") {
form.setFieldsValue({
name: template.name,
description: template.description,
dataType: template.dataType,
labelingType: template.labelingType,
style: template.style,
category: template.category,
labels: template.configuration.labels,
objects: template.configuration.objects,
});
} else if (visible && mode === "create") {
form.resetFields();
// Set default values
form.setFieldsValue({
style: "horizontal",
category: "custom",
labels: [],
objects: [{ name: "image", type: "Image", value: "$image" }],
});
}
}, [visible, template, mode, form]);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setLoading(true);
console.log("Form values:", values);
const requestData = {
name: values.name,
description: values.description,
dataType: values.dataType,
labelingType: values.labelingType,
style: values.style,
category: values.category,
configuration: {
labels: values.labels,
objects: values.objects,
},
};
console.log("Request data:", requestData);
let response;
if (mode === "create") {
response = await createAnnotationTemplateUsingPost(requestData);
} else {
response = await updateAnnotationTemplateByIdUsingPut(template!.id, requestData);
}
if (response.code === 200) {
message.success(`模板${mode === "create" ? "创建" : "更新"}成功`);
form.resetFields();
onSuccess();
} else {
message.error(response.message || `模板${mode === "create" ? "创建" : "更新"}失败`);
}
} catch (error: any) {
if (error.errorFields) {
message.error("请填写所有必填字段");
} else {
message.error(`模板${mode === "create" ? "创建" : "更新"}失败`);
console.error(error);
}
} finally {
setLoading(false);
}
};
const needsOptions = (type: string) => {
return ["Choices", "RectangleLabels", "PolygonLabels", "Labels"].includes(type);
};
return (
<Modal
title={mode === "create" ? "创建模板" : "编辑模板"}
open={visible}
onCancel={onCancel}
onOk={handleSubmit}
confirmLoading={loading}
width={900}
destroyOnClose
>
<Form
form={form}
layout="vertical"
style={{ maxHeight: "70vh", overflowY: "auto", paddingRight: 8 }}
>
<Form.Item
label="模板名称"
name="name"
rules={[{ required: true, message: "请输入模板名称" }]}
>
<Input placeholder="例如:产品质量分类" maxLength={100} />
</Form.Item>
<Form.Item label="描述" name="description">
<TextArea
placeholder="描述此模板的用途"
rows={2}
maxLength={500}
/>
</Form.Item>
<Space style={{ width: "100%" }} size="large">
<Form.Item
label="数据类型"
name="dataType"
rules={[{ required: true, message: "请选择数据类型" }]}
style={{ width: 200 }}
>
<Select placeholder="选择数据类型">
<Option value="image"></Option>
<Option value="text"></Option>
<Option value="audio"></Option>
<Option value="video"></Option>
</Select>
</Form.Item>
<Form.Item
label="标注类型"
name="labelingType"
rules={[{ required: true, message: "请选择标注类型" }]}
style={{ width: 220 }}
>
<Select placeholder="选择标注类型">
<Option value="classification"></Option>
<Option value="object-detection"></Option>
<Option value="segmentation"></Option>
<Option value="ner"></Option>
<Option value="multi-stage"></Option>
</Select>
</Form.Item>
<Form.Item
label="样式"
name="style"
style={{ width: 150 }}
>
<Select>
<Option value="horizontal"></Option>
<Option value="vertical"></Option>
</Select>
</Form.Item>
<Form.Item
label="分类"
name="category"
style={{ width: 180 }}
>
<Select>
<Option value="computer-vision"></Option>
<Option value="nlp"></Option>
<Option value="audio"></Option>
<Option value="quality-control"></Option>
<Option value="custom"></Option>
</Select>
</Form.Item>
</Space>
<Divider></Divider>
<Form.List name="objects">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Card key={field.key} size="small" style={{ marginBottom: 8 }}>
<Space align="start" style={{ width: "100%" }}>
<Form.Item
{...field}
label="名称"
name={[field.name, "name"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0, width: 150 }}
>
<Input placeholder="例如:image" />
</Form.Item>
<Form.Item
{...field}
label="类型"
name={[field.name, "type"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0, width: 150 }}
>
<TagSelector type="object" />
</Form.Item>
<Form.Item
{...field}
label="值"
name={[field.name, "value"]}
rules={[
{ required: true, message: "必填" },
{ pattern: /^\$/, message: "必须以 $ 开头" },
]}
style={{ marginBottom: 0, width: 150 }}
>
<Input placeholder="$image" />
</Form.Item>
{fields.length > 1 && (
<MinusCircleOutlined
style={{ marginTop: 30, color: "red" }}
onClick={() => remove(field.name)}
/>
)}
</Space>
</Card>
))}
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
</Button>
</>
)}
</Form.List>
<Divider></Divider>
<Form.List name="labels">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Card
key={field.key}
size="small"
style={{ marginBottom: 12 }}
title={
<Space>
<span> {fields.indexOf(field) + 1}</span>
<Form.Item noStyle shouldUpdate>
{() => {
const controlType = form.getFieldValue(["labels", field.name, "type"]);
const fromName = form.getFieldValue(["labels", field.name, "fromName"]);
if (controlType || fromName) {
return (
<span style={{ fontSize: 12, fontWeight: 'normal', color: '#999' }}>
({fromName || '未命名'} - {controlType || '未设置类型'})
</span>
);
}
return null;
}}
</Form.Item>
</Space>
}
extra={
<MinusCircleOutlined
style={{ color: "red" }}
onClick={() => remove(field.name)}
/>
}
>
<Space direction="vertical" style={{ width: "100%" }} size="middle">
{/* Row 1: 控件名称, 标注目标对象, 控件类型 */}
<div style={{ display: 'grid', gridTemplateColumns: '180px 220px 1fr auto', gap: 12, alignItems: 'flex-end' }}>
<Form.Item
{...field}
label="来源名称"
name={[field.name, "fromName"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0 }}
tooltip="此控件的唯一标识符"
>
<Input placeholder="例如:choice" />
</Form.Item>
<Form.Item
{...field}
label="标注目标对象"
name={[field.name, "toName"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0 }}
tooltip="选择此控件将标注哪个数据对象"
dependencies={['objects']}
>
<Select placeholder="选择数据对象">
{(form.getFieldValue("objects") || []).map((obj: any, idx: number) => (
<Option key={idx} value={obj?.name || ''}>
{obj?.name || `对象 ${idx + 1}`} ({obj?.type || '未知类型'})
</Option>
))}
</Select>
</Form.Item>
<Form.Item
{...field}
label="控件类型"
name={[field.name, "type"]}
rules={[{ required: true, message: "必填" }]}
style={{ marginBottom: 0 }}
>
<TagSelector type="control" />
</Form.Item>
<Form.Item
{...field}
label=" "
name={[field.name, "required"]}
valuePropName="checked"
style={{ marginBottom: 0 }}
>
<Checkbox></Checkbox>
</Form.Item>
</div>
{/* Row 2: 取值范围定义(添加选项) - Conditionally rendered based on type */}
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) => {
const prevType = prevValues.labels?.[field.name]?.type;
const currType = currentValues.labels?.[field.name]?.type;
return prevType !== currType;
}}
>
{({ getFieldValue }) => {
const controlType = getFieldValue(["labels", field.name, "type"]);
const fieldName = controlType === "Choices" ? "options" : "labels";
if (needsOptions(controlType)) {
return (
<Form.Item
{...field}
label={controlType === "Choices" ? "选项" : "标签"}
name={[field.name, fieldName]}
rules={[{ required: true, message: "至少需要一个选项" }]}
style={{ marginBottom: 0 }}
>
<Select
mode="tags"
open={false}
placeholder={
controlType === "Choices"
? "输入选项内容,按回车添加。例如:是、否、不确定"
: "输入标签名称,按回车添加。例如:人物、车辆、建筑物"
}
style={{ width: "100%" }}
/>
</Form.Item>
);
}
return null;
}}
</Form.Item>
{/* Row 3: 描述 */}
<Form.Item
{...field}
label="描述"
name={[field.name, "description"]}
style={{ marginBottom: 0 }}
tooltip="向标注人员显示的帮助信息"
>
<Input placeholder="为标注人员提供此控件的使用说明" maxLength={200} />
</Form.Item>
</Space>
</Card>
))}
<Button
type="dashed"
onClick={() =>
add({
fromName: "",
toName: "",
type: "Choices",
required: false,
})
}
block
icon={<PlusOutlined />}
>
</Button>
</>
)}
</Form.List>
</Form>
</Modal>
);
};
export default TemplateForm;

View File

@@ -1,311 +1,311 @@
import React, { useState } from "react";
import {
Button,
Table,
Space,
Tag,
message,
Tooltip,
Popconfirm,
Card,
} from "antd";
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
EyeOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import {
queryAnnotationTemplatesUsingGet,
deleteAnnotationTemplateByIdUsingDelete,
} from "../annotation.api";
import type { AnnotationTemplate } from "../annotation.model";
import TemplateForm from "./TemplateForm.tsx";
import TemplateDetail from "./TemplateDetail.tsx";
import {SearchControls} from "@/components/SearchControls.tsx";
import useFetchData from "@/hooks/useFetchData.ts";
import {
AnnotationTypeMap,
ClassificationMap,
DataTypeMap,
TemplateTypeMap
} from "@/pages/DataAnnotation/annotation.const.tsx";
const TemplateList: React.FC = () => {
const filterOptions = [
{
key: "category",
label: "分类",
options: [...Object.values(ClassificationMap)],
},
{
key: "dataType",
label: "数据类型",
options: [...Object.values(DataTypeMap)],
},
{
key: "labelingType",
label: "标注类型",
options: [...Object.values(AnnotationTypeMap)],
},
{
key: "builtIn",
label: "模板类型",
options: [...Object.values(TemplateTypeMap)],
},
];
// Modals
const [isFormVisible, setIsFormVisible] = useState(false);
const [isDetailVisible, setIsDetailVisible] = useState(false);
const [selectedTemplate, setSelectedTemplate] = useState<AnnotationTemplate | undefined>();
const [formMode, setFormMode] = useState<"create" | "edit">("create");
const {
loading,
tableData,
pagination,
searchParams,
setSearchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryAnnotationTemplatesUsingGet, undefined, undefined, undefined, undefined, 0);
const handleCreate = () => {
setFormMode("create");
setSelectedTemplate(undefined);
setIsFormVisible(true);
};
const handleEdit = (template: AnnotationTemplate) => {
setFormMode("edit");
setSelectedTemplate(template);
setIsFormVisible(true);
};
const handleView = (template: AnnotationTemplate) => {
setSelectedTemplate(template);
setIsDetailVisible(true);
};
const handleDelete = async (templateId: string) => {
try {
const response = await deleteAnnotationTemplateByIdUsingDelete(templateId);
if (response.code === 200) {
message.success("模板删除成功");
fetchData();
} else {
message.error(response.message || "删除模板失败");
}
} catch (error) {
message.error("删除模板失败");
console.error(error);
}
};
const handleFormSuccess = () => {
setIsFormVisible(false);
fetchData();
};
const getCategoryColor = (category: string) => {
const colors: Record<string, string> = {
"computer-vision": "blue",
"nlp": "green",
"audio": "purple",
"quality-control": "orange",
"custom": "default",
};
return colors[category] || "default";
};
const columns: ColumnsType<AnnotationTemplate> = [
{
title: "模板名称",
dataIndex: "name",
key: "name",
width: 200,
ellipsis: true,
onFilter: (value, record) =>
record.name.toLowerCase().includes(value.toString().toLowerCase()) ||
(record.description?.toLowerCase().includes(value.toString().toLowerCase()) ?? false),
},
{
title: "描述",
dataIndex: "description",
key: "description",
ellipsis: {
showTitle: false,
},
render: (description: string) => (
<Tooltip title={description}>
<div
style={{
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'normal',
lineHeight: '1.5em',
maxHeight: '3em',
}}
>
{description}
</div>
</Tooltip>
),
},
{
title: "数据类型",
dataIndex: "dataType",
key: "dataType",
width: 120,
render: (dataType: string) => (
<Tag color="cyan">{dataType}</Tag>
),
},
{
title: "标注类型",
dataIndex: "labelingType",
key: "labelingType",
width: 150,
render: (labelingType: string) => (
<Tag color="geekblue">{labelingType}</Tag>
),
},
{
title: "分类",
dataIndex: "category",
key: "category",
width: 150,
render: (category: string) => (
<Tag color={getCategoryColor(category)}>{category}</Tag>
),
},
{
title: "类型",
dataIndex: "builtIn",
key: "builtIn",
width: 100,
render: (builtIn: boolean) => (
<Tag color={builtIn ? "gold" : "default"}>
{builtIn ? "系统内置" : "自定义"}
</Tag>
),
},
{
title: "版本",
dataIndex: "version",
key: "version",
width: 80,
},
{
title: "创建时间",
dataIndex: "createdAt",
key: "createdAt",
width: 180,
render: (date: string) => new Date(date).toLocaleString(),
},
{
title: "操作",
key: "action",
width: 200,
fixed: "right",
render: (_, record) => (
<Space size="small">
<Tooltip title="查看详情">
<Button
type="link"
icon={<EyeOutlined />}
onClick={() => handleView(record)}
/>
</Tooltip>
{!record.builtIn && (
<>
<Tooltip title="编辑">
<Button
type="link"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
/>
</Tooltip>
<Popconfirm
title="确定要删除这个模板吗?"
onConfirm={() => handleDelete(record.id)}
okText="确定"
cancelText="取消"
>
<Tooltip title="删除">
<Button
type="link"
danger
icon={<DeleteOutlined />}
/>
</Tooltip>
</Popconfirm>
</>
)}
</Space>
),
},
];
return (
<div className="flex flex-col gap-4">
{/* Search, Filters and Buttons in one row */}
<div className="flex items-center justify-between gap-2">
{/* Left side: Search and Filters */}
<div className="flex items-center gap-2 flex-wrap">
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索任务名称、描述"
filters={filterOptions}
onFiltersChange={handleFiltersChange}
showViewToggle={true}
onReload={fetchData}
onClearFilters={() => setSearchParams({ ...searchParams, filter: {} })}
/>
</div>
{/* Right side: Create button */}
<div className="flex items-center gap-2">
<Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
</Button>
</div>
</div>
<Card>
<Table
columns={columns}
dataSource={tableData}
rowKey="id"
loading={loading}
pagination={pagination}
scroll={{ x: 1400, y: "calc(100vh - 24rem)" }}
/>
</Card>
<TemplateForm
visible={isFormVisible}
mode={formMode}
template={selectedTemplate}
onSuccess={handleFormSuccess}
onCancel={() => setIsFormVisible(false)}
/>
<TemplateDetail
visible={isDetailVisible}
template={selectedTemplate}
onClose={() => setIsDetailVisible(false)}
/>
</div>
);
};
export default TemplateList;
export { TemplateList };
import React, { useState } from "react";
import {
Button,
Table,
Space,
Tag,
message,
Tooltip,
Popconfirm,
Card,
} from "antd";
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
EyeOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import {
queryAnnotationTemplatesUsingGet,
deleteAnnotationTemplateByIdUsingDelete,
} from "../annotation.api";
import type { AnnotationTemplate } from "../annotation.model";
import TemplateForm from "./TemplateForm.tsx";
import TemplateDetail from "./TemplateDetail.tsx";
import {SearchControls} from "@/components/SearchControls.tsx";
import useFetchData from "@/hooks/useFetchData.ts";
import {
AnnotationTypeMap,
ClassificationMap,
DataTypeMap,
TemplateTypeMap
} from "@/pages/DataAnnotation/annotation.const.tsx";
const TemplateList: React.FC = () => {
const filterOptions = [
{
key: "category",
label: "分类",
options: [...Object.values(ClassificationMap)],
},
{
key: "dataType",
label: "数据类型",
options: [...Object.values(DataTypeMap)],
},
{
key: "labelingType",
label: "标注类型",
options: [...Object.values(AnnotationTypeMap)],
},
{
key: "builtIn",
label: "模板类型",
options: [...Object.values(TemplateTypeMap)],
},
];
// Modals
const [isFormVisible, setIsFormVisible] = useState(false);
const [isDetailVisible, setIsDetailVisible] = useState(false);
const [selectedTemplate, setSelectedTemplate] = useState<AnnotationTemplate | undefined>();
const [formMode, setFormMode] = useState<"create" | "edit">("create");
const {
loading,
tableData,
pagination,
searchParams,
setSearchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryAnnotationTemplatesUsingGet, undefined, undefined, undefined, undefined, 0);
const handleCreate = () => {
setFormMode("create");
setSelectedTemplate(undefined);
setIsFormVisible(true);
};
const handleEdit = (template: AnnotationTemplate) => {
setFormMode("edit");
setSelectedTemplate(template);
setIsFormVisible(true);
};
const handleView = (template: AnnotationTemplate) => {
setSelectedTemplate(template);
setIsDetailVisible(true);
};
const handleDelete = async (templateId: string) => {
try {
const response = await deleteAnnotationTemplateByIdUsingDelete(templateId);
if (response.code === 200) {
message.success("模板删除成功");
fetchData();
} else {
message.error(response.message || "删除模板失败");
}
} catch (error) {
message.error("删除模板失败");
console.error(error);
}
};
const handleFormSuccess = () => {
setIsFormVisible(false);
fetchData();
};
const getCategoryColor = (category: string) => {
const colors: Record<string, string> = {
"computer-vision": "blue",
"nlp": "green",
"audio": "purple",
"quality-control": "orange",
"custom": "default",
};
return colors[category] || "default";
};
const columns: ColumnsType<AnnotationTemplate> = [
{
title: "模板名称",
dataIndex: "name",
key: "name",
width: 200,
ellipsis: true,
onFilter: (value, record) =>
record.name.toLowerCase().includes(value.toString().toLowerCase()) ||
(record.description?.toLowerCase().includes(value.toString().toLowerCase()) ?? false),
},
{
title: "描述",
dataIndex: "description",
key: "description",
ellipsis: {
showTitle: false,
},
render: (description: string) => (
<Tooltip title={description}>
<div
style={{
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'normal',
lineHeight: '1.5em',
maxHeight: '3em',
}}
>
{description}
</div>
</Tooltip>
),
},
{
title: "数据类型",
dataIndex: "dataType",
key: "dataType",
width: 120,
render: (dataType: string) => (
<Tag color="cyan">{dataType}</Tag>
),
},
{
title: "标注类型",
dataIndex: "labelingType",
key: "labelingType",
width: 150,
render: (labelingType: string) => (
<Tag color="geekblue">{labelingType}</Tag>
),
},
{
title: "分类",
dataIndex: "category",
key: "category",
width: 150,
render: (category: string) => (
<Tag color={getCategoryColor(category)}>{category}</Tag>
),
},
{
title: "类型",
dataIndex: "builtIn",
key: "builtIn",
width: 100,
render: (builtIn: boolean) => (
<Tag color={builtIn ? "gold" : "default"}>
{builtIn ? "系统内置" : "自定义"}
</Tag>
),
},
{
title: "版本",
dataIndex: "version",
key: "version",
width: 80,
},
{
title: "创建时间",
dataIndex: "createdAt",
key: "createdAt",
width: 180,
render: (date: string) => new Date(date).toLocaleString(),
},
{
title: "操作",
key: "action",
width: 200,
fixed: "right",
render: (_, record) => (
<Space size="small">
<Tooltip title="查看详情">
<Button
type="link"
icon={<EyeOutlined />}
onClick={() => handleView(record)}
/>
</Tooltip>
{!record.builtIn && (
<>
<Tooltip title="编辑">
<Button
type="link"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
/>
</Tooltip>
<Popconfirm
title="确定要删除这个模板吗?"
onConfirm={() => handleDelete(record.id)}
okText="确定"
cancelText="取消"
>
<Tooltip title="删除">
<Button
type="link"
danger
icon={<DeleteOutlined />}
/>
</Tooltip>
</Popconfirm>
</>
)}
</Space>
),
},
];
return (
<div className="flex flex-col gap-4">
{/* Search, Filters and Buttons in one row */}
<div className="flex items-center justify-between gap-2">
{/* Left side: Search and Filters */}
<div className="flex items-center gap-2 flex-wrap">
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索任务名称、描述"
filters={filterOptions}
onFiltersChange={handleFiltersChange}
showViewToggle={true}
onReload={fetchData}
onClearFilters={() => setSearchParams({ ...searchParams, filter: {} })}
/>
</div>
{/* Right side: Create button */}
<div className="flex items-center gap-2">
<Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
</Button>
</div>
</div>
<Card>
<Table
columns={columns}
dataSource={tableData}
rowKey="id"
loading={loading}
pagination={pagination}
scroll={{ x: 1400, y: "calc(100vh - 24rem)" }}
/>
</Card>
<TemplateForm
visible={isFormVisible}
mode={formMode}
template={selectedTemplate}
onSuccess={handleFormSuccess}
onCancel={() => setIsFormVisible(false)}
/>
<TemplateDetail
visible={isDetailVisible}
template={selectedTemplate}
onClose={() => setIsDetailVisible(false)}
/>
</div>
);
};
export default TemplateList;
export { TemplateList };

View File

@@ -1,161 +1,161 @@
import React, { useState } from "react";
import {
Card,
Button,
Space,
Row,
Col,
Drawer,
Typography,
message,
} from "antd";
import {
PlusOutlined,
EyeOutlined,
CodeOutlined,
AppstoreOutlined,
} from "@ant-design/icons";
import { TagBrowser } from "./components";
const { Paragraph } = Typography;
interface VisualTemplateBuilderProps {
onSave?: (templateCode: string) => void;
}
/**
* Visual Template Builder
* Provides a drag-and-drop interface for building Label Studio templates
*/
const VisualTemplateBuilder: React.FC<VisualTemplateBuilderProps> = ({
onSave,
}) => {
const [drawerVisible, setDrawerVisible] = useState(false);
const [previewVisible, setPreviewVisible] = useState(false);
const [selectedTags, setSelectedTags] = useState<
Array<{ name: string; category: "object" | "control" }>
>([]);
const handleTagSelect = (tagName: string, category: "object" | "control") => {
message.info(`选择了 ${category === "object" ? "对象" : "控件"}: ${tagName}`);
setSelectedTags([...selectedTags, { name: tagName, category }]);
setDrawerVisible(false);
};
const handleSave = () => {
// TODO: Generate template XML from selectedTags
message.success("模板保存成功");
onSave?.("<View><!-- Generated template --></View>");
};
return (
<div style={{ padding: "24px" }}>
<Row gutter={16}>
<Col span={24}>
<Card
title="可视化模板构建器"
extra={
<Space>
<Button
icon={<AppstoreOutlined />}
onClick={() => setDrawerVisible(true)}
>
</Button>
<Button
icon={<CodeOutlined />}
onClick={() => setPreviewVisible(true)}
>
</Button>
<Button
type="primary"
icon={<EyeOutlined />}
onClick={handleSave}
>
</Button>
</Space>
}
>
<div
style={{
minHeight: "400px",
border: "2px dashed #d9d9d9",
borderRadius: "8px",
padding: "24px",
textAlign: "center",
}}
>
{selectedTags.length === 0 ? (
<div>
<Paragraph type="secondary">
"浏览标签"
</Paragraph>
<Button
type="dashed"
icon={<PlusOutlined />}
onClick={() => setDrawerVisible(true)}
>
</Button>
</div>
) : (
<Space direction="vertical" size="large">
{selectedTags.map((tag, index) => (
<Card key={index} size="small">
<div>
{tag.category === "object" ? "对象" : "控件"}: {tag.name}
</div>
</Card>
))}
</Space>
)}
</div>
</Card>
</Col>
</Row>
<Drawer
title="标签浏览器"
placement="right"
width={800}
open={drawerVisible}
onClose={() => setDrawerVisible(false)}
>
<TagBrowser onTagSelect={handleTagSelect} />
</Drawer>
<Drawer
title="模板代码预览"
placement="right"
width={600}
open={previewVisible}
onClose={() => setPreviewVisible(false)}
>
<pre
style={{
background: "#f5f5f5",
padding: "16px",
borderRadius: "4px",
overflow: "auto",
}}
>
<code>
{`<View>
<!-- 根据选择的标签生成的模板代码 -->
${selectedTags
.map(
(tag) =>
`<${tag.name}${tag.category === "object" ? ' name="obj" value="$data"' : ' name="ctrl" toName="obj"'} />`
)
.join("\n ")}
</View>`}
</code>
</pre>
</Drawer>
</div>
);
};
export default VisualTemplateBuilder;
import React, { useState } from "react";
import {
Card,
Button,
Space,
Row,
Col,
Drawer,
Typography,
message,
} from "antd";
import {
PlusOutlined,
EyeOutlined,
CodeOutlined,
AppstoreOutlined,
} from "@ant-design/icons";
import { TagBrowser } from "./components";
const { Paragraph } = Typography;
interface VisualTemplateBuilderProps {
onSave?: (templateCode: string) => void;
}
/**
* Visual Template Builder
* Provides a drag-and-drop interface for building Label Studio templates
*/
const VisualTemplateBuilder: React.FC<VisualTemplateBuilderProps> = ({
onSave,
}) => {
const [drawerVisible, setDrawerVisible] = useState(false);
const [previewVisible, setPreviewVisible] = useState(false);
const [selectedTags, setSelectedTags] = useState<
Array<{ name: string; category: "object" | "control" }>
>([]);
const handleTagSelect = (tagName: string, category: "object" | "control") => {
message.info(`选择了 ${category === "object" ? "对象" : "控件"}: ${tagName}`);
setSelectedTags([...selectedTags, { name: tagName, category }]);
setDrawerVisible(false);
};
const handleSave = () => {
// TODO: Generate template XML from selectedTags
message.success("模板保存成功");
onSave?.("<View><!-- Generated template --></View>");
};
return (
<div style={{ padding: "24px" }}>
<Row gutter={16}>
<Col span={24}>
<Card
title="可视化模板构建器"
extra={
<Space>
<Button
icon={<AppstoreOutlined />}
onClick={() => setDrawerVisible(true)}
>
</Button>
<Button
icon={<CodeOutlined />}
onClick={() => setPreviewVisible(true)}
>
</Button>
<Button
type="primary"
icon={<EyeOutlined />}
onClick={handleSave}
>
</Button>
</Space>
}
>
<div
style={{
minHeight: "400px",
border: "2px dashed #d9d9d9",
borderRadius: "8px",
padding: "24px",
textAlign: "center",
}}
>
{selectedTags.length === 0 ? (
<div>
<Paragraph type="secondary">
"浏览标签"
</Paragraph>
<Button
type="dashed"
icon={<PlusOutlined />}
onClick={() => setDrawerVisible(true)}
>
</Button>
</div>
) : (
<Space direction="vertical" size="large">
{selectedTags.map((tag, index) => (
<Card key={index} size="small">
<div>
{tag.category === "object" ? "对象" : "控件"}: {tag.name}
</div>
</Card>
))}
</Space>
)}
</div>
</Card>
</Col>
</Row>
<Drawer
title="标签浏览器"
placement="right"
width={800}
open={drawerVisible}
onClose={() => setDrawerVisible(false)}
>
<TagBrowser onTagSelect={handleTagSelect} />
</Drawer>
<Drawer
title="模板代码预览"
placement="right"
width={600}
open={previewVisible}
onClose={() => setPreviewVisible(false)}
>
<pre
style={{
background: "#f5f5f5",
padding: "16px",
borderRadius: "4px",
overflow: "auto",
}}
>
<code>
{`<View>
<!-- 根据选择的标签生成的模板代码 -->
${selectedTags
.map(
(tag) =>
`<${tag.name}${tag.category === "object" ? ' name="obj" value="$data"' : ' name="ctrl" toName="obj"'} />`
)
.join("\n ")}
</View>`}
</code>
</pre>
</Drawer>
</div>
);
};
export default VisualTemplateBuilder;

View File

@@ -1,260 +1,260 @@
import React from "react";
import { Card, Tabs, List, Tag, Typography, Space, Empty, Spin } from "antd";
import {
AppstoreOutlined,
ControlOutlined,
InfoCircleOutlined,
} from "@ant-design/icons";
import { useTagConfig } from "../../../../hooks/useTagConfig";
import {
getControlDisplayName,
getObjectDisplayName,
getControlGroups,
} from "../../annotation.tagconfig";
import type { TagOption } from "../../annotation.tagconfig";
const { Title, Paragraph, Text } = Typography;
interface TagBrowserProps {
onTagSelect?: (tagName: string, category: "object" | "control") => void;
}
/**
* Tag Browser Component
* Displays all available Label Studio tags in a browsable interface
*/
const TagBrowser: React.FC<TagBrowserProps> = ({ onTagSelect }) => {
const { config, objectOptions, controlOptions, loading, error } =
useTagConfig();
if (loading) {
return (
<Card>
<div style={{ textAlign: "center", padding: "40px" }}>
<Spin size="large" />
<div style={{ marginTop: 16 }}>...</div>
</div>
</Card>
);
}
if (error) {
return (
<Card>
<Empty
description={
<div>
<div>{error}</div>
<Text type="secondary"></Text>
</div>
}
/>
</Card>
);
}
const renderObjectList = () => (
<List
grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }}
dataSource={objectOptions}
renderItem={(item: TagOption) => {
const objConfig = config?.objects[item.value];
return (
<List.Item>
<Card
hoverable
size="small"
onClick={() => onTagSelect?.(item.value, "object")}
style={{ height: "100%" }}
>
<Space direction="vertical" size="small" style={{ width: "100%" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<Text strong>{getObjectDisplayName(item.value)}</Text>
<Tag color="blue">&lt;{item.value}&gt;</Tag>
</div>
<Text type="secondary" style={{ fontSize: 12 }}>
{item.description}
</Text>
{objConfig && (
<div style={{ marginTop: 8 }}>
<Text style={{ fontSize: 11, color: "#8c8c8c" }}>
:{" "}
{objConfig.required_attrs.join(", ") || "无"}
</Text>
</div>
)}
</Space>
</Card>
</List.Item>
);
}}
/>
);
const renderControlsByGroup = () => {
const groups = getControlGroups();
return (
<Tabs
defaultActiveKey="classification"
items={Object.entries(groups).map(([groupKey, groupConfig]) => {
const groupControls = controlOptions.filter((opt: TagOption) =>
groupConfig.controls.includes(opt.value)
);
return {
key: groupKey,
label: groupConfig.label,
children: (
<List
grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }}
dataSource={groupControls}
locale={{ emptyText: "此分组暂无控件" }}
renderItem={(item: TagOption) => {
const ctrlConfig = config?.controls[item.value];
return (
<List.Item>
<Card
hoverable
size="small"
onClick={() => onTagSelect?.(item.value, "control")}
style={{ height: "100%" }}
>
<Space direction="vertical" size="small" style={{ width: "100%" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<Text strong>
{getControlDisplayName(item.value)}
</Text>
<Tag color="green">&lt;{item.value}&gt;</Tag>
</div>
<Text type="secondary" style={{ fontSize: 12 }}>
{item.description}
</Text>
{ctrlConfig && (
<Space
size={4}
wrap
style={{ marginTop: 8 }}
>
{ctrlConfig.requires_children && (
<Tag
color="orange"
style={{ fontSize: 10, margin: 0 }}
>
&lt;{ctrlConfig.child_tag}&gt;
</Tag>
)}
{ctrlConfig.required_attrs.includes("toName") && (
<Tag
color="purple"
style={{ fontSize: 10, margin: 0 }}
>
</Tag>
)}
</Space>
)}
</Space>
</Card>
</List.Item>
);
}}
/>
),
};
})}
/>
);
};
return (
<Card>
<Tabs
defaultActiveKey="controls"
items={[
{
key: "controls",
label: (
<span>
<ControlOutlined />
({controlOptions.length})
</span>
),
children: renderControlsByGroup(),
},
{
key: "objects",
label: (
<span>
<AppstoreOutlined />
({objectOptions.length})
</span>
),
children: renderObjectList(),
},
{
key: "help",
label: (
<span>
<InfoCircleOutlined />
使
</span>
),
children: (
<div style={{ padding: "16px" }}>
<Title level={4}>Label Studio </Title>
<Paragraph>
</Paragraph>
<ul>
<li>
<Text strong></Text>
</li>
<li>
<Text strong></Text>
</li>
</ul>
<Title level={5} style={{ marginTop: 24 }}>
</Title>
<Paragraph>
<pre style={{ background: "#f5f5f5", padding: 12, borderRadius: 4 }}>
{`<View>
<!-- 数据对象 -->
<Image name="image" value="$image" />
<!-- 控件 -->
<RectangleLabels name="label" toName="image">
<Label value="人物" />
<Label value="车辆" />
</RectangleLabels>
</View>`}
</pre>
</Paragraph>
<Title level={5} style={{ marginTop: 24 }}>
</Title>
<ul>
<li>
<Text code>name</Text>
</li>
<li>
<Text code>toName</Text> name
</li>
<li>
<Text code>value</Text> $ $image, $text
</li>
<li>
<Text code>required</Text>
</li>
</ul>
</div>
),
},
]}
/>
</Card>
);
};
export default TagBrowser;
import React from "react";
import { Card, Tabs, List, Tag, Typography, Space, Empty, Spin } from "antd";
import {
AppstoreOutlined,
ControlOutlined,
InfoCircleOutlined,
} from "@ant-design/icons";
import { useTagConfig } from "../../../../hooks/useTagConfig";
import {
getControlDisplayName,
getObjectDisplayName,
getControlGroups,
} from "../../annotation.tagconfig";
import type { TagOption } from "../../annotation.tagconfig";
const { Title, Paragraph, Text } = Typography;
interface TagBrowserProps {
onTagSelect?: (tagName: string, category: "object" | "control") => void;
}
/**
* Tag Browser Component
* Displays all available Label Studio tags in a browsable interface
*/
const TagBrowser: React.FC<TagBrowserProps> = ({ onTagSelect }) => {
const { config, objectOptions, controlOptions, loading, error } =
useTagConfig();
if (loading) {
return (
<Card>
<div style={{ textAlign: "center", padding: "40px" }}>
<Spin size="large" />
<div style={{ marginTop: 16 }}>...</div>
</div>
</Card>
);
}
if (error) {
return (
<Card>
<Empty
description={
<div>
<div>{error}</div>
<Text type="secondary"></Text>
</div>
}
/>
</Card>
);
}
const renderObjectList = () => (
<List
grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }}
dataSource={objectOptions}
renderItem={(item: TagOption) => {
const objConfig = config?.objects[item.value];
return (
<List.Item>
<Card
hoverable
size="small"
onClick={() => onTagSelect?.(item.value, "object")}
style={{ height: "100%" }}
>
<Space direction="vertical" size="small" style={{ width: "100%" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<Text strong>{getObjectDisplayName(item.value)}</Text>
<Tag color="blue">&lt;{item.value}&gt;</Tag>
</div>
<Text type="secondary" style={{ fontSize: 12 }}>
{item.description}
</Text>
{objConfig && (
<div style={{ marginTop: 8 }}>
<Text style={{ fontSize: 11, color: "#8c8c8c" }}>
:{" "}
{objConfig.required_attrs.join(", ") || "无"}
</Text>
</div>
)}
</Space>
</Card>
</List.Item>
);
}}
/>
);
const renderControlsByGroup = () => {
const groups = getControlGroups();
return (
<Tabs
defaultActiveKey="classification"
items={Object.entries(groups).map(([groupKey, groupConfig]) => {
const groupControls = controlOptions.filter((opt: TagOption) =>
groupConfig.controls.includes(opt.value)
);
return {
key: groupKey,
label: groupConfig.label,
children: (
<List
grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }}
dataSource={groupControls}
locale={{ emptyText: "此分组暂无控件" }}
renderItem={(item: TagOption) => {
const ctrlConfig = config?.controls[item.value];
return (
<List.Item>
<Card
hoverable
size="small"
onClick={() => onTagSelect?.(item.value, "control")}
style={{ height: "100%" }}
>
<Space direction="vertical" size="small" style={{ width: "100%" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<Text strong>
{getControlDisplayName(item.value)}
</Text>
<Tag color="green">&lt;{item.value}&gt;</Tag>
</div>
<Text type="secondary" style={{ fontSize: 12 }}>
{item.description}
</Text>
{ctrlConfig && (
<Space
size={4}
wrap
style={{ marginTop: 8 }}
>
{ctrlConfig.requires_children && (
<Tag
color="orange"
style={{ fontSize: 10, margin: 0 }}
>
&lt;{ctrlConfig.child_tag}&gt;
</Tag>
)}
{ctrlConfig.required_attrs.includes("toName") && (
<Tag
color="purple"
style={{ fontSize: 10, margin: 0 }}
>
</Tag>
)}
</Space>
)}
</Space>
</Card>
</List.Item>
);
}}
/>
),
};
})}
/>
);
};
return (
<Card>
<Tabs
defaultActiveKey="controls"
items={[
{
key: "controls",
label: (
<span>
<ControlOutlined />
({controlOptions.length})
</span>
),
children: renderControlsByGroup(),
},
{
key: "objects",
label: (
<span>
<AppstoreOutlined />
({objectOptions.length})
</span>
),
children: renderObjectList(),
},
{
key: "help",
label: (
<span>
<InfoCircleOutlined />
使
</span>
),
children: (
<div style={{ padding: "16px" }}>
<Title level={4}>Label Studio </Title>
<Paragraph>
</Paragraph>
<ul>
<li>
<Text strong></Text>
</li>
<li>
<Text strong></Text>
</li>
</ul>
<Title level={5} style={{ marginTop: 24 }}>
</Title>
<Paragraph>
<pre style={{ background: "#f5f5f5", padding: 12, borderRadius: 4 }}>
{`<View>
<!-- 数据对象 -->
<Image name="image" value="$image" />
<!-- 控件 -->
<RectangleLabels name="label" toName="image">
<Label value="人物" />
<Label value="车辆" />
</RectangleLabels>
</View>`}
</pre>
</Paragraph>
<Title level={5} style={{ marginTop: 24 }}>
</Title>
<ul>
<li>
<Text code>name</Text>
</li>
<li>
<Text code>toName</Text> name
</li>
<li>
<Text code>value</Text> $ $image, $text
</li>
<li>
<Text code>required</Text>
</li>
</ul>
</div>
),
},
]}
/>
</Card>
);
};
export default TagBrowser;

View File

@@ -1,301 +1,301 @@
import React, { useState, useEffect } from "react";
import { Select, Tooltip, Spin, Collapse, Tag, Space } from "antd";
import { InfoCircleOutlined } from "@ant-design/icons";
import { getTagConfigUsingGet } from "../../annotation.api";
import type {
LabelStudioTagConfig,
TagOption,
} from "../../annotation.tagconfig";
import {
parseTagConfig,
getControlDisplayName,
getObjectDisplayName,
getControlGroups,
} from "../../annotation.tagconfig";
const { Option, OptGroup } = Select;
interface TagSelectorProps {
value?: string;
onChange?: (value: string) => void;
type: "object" | "control";
placeholder?: string;
style?: React.CSSProperties;
disabled?: boolean;
}
/**
* Tag Selector Component
* Dynamically fetches and displays available Label Studio tags from backend config
*/
const TagSelector: React.FC<TagSelectorProps> = ({
value,
onChange,
type,
placeholder,
style,
disabled,
}) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [tagOptions, setTagOptions] = useState<TagOption[]>([]);
useEffect(() => {
fetchTagConfig();
}, []);
const fetchTagConfig = async () => {
setLoading(true);
setError(null);
try {
const response = await getTagConfigUsingGet();
if (response.code === 200 && response.data) {
const config: LabelStudioTagConfig = response.data;
const { objectOptions, controlOptions } = parseTagConfig(config);
if (type === "object") {
setTagOptions(objectOptions);
} else {
setTagOptions(controlOptions);
}
} else {
setError(response.message || "获取标签配置失败");
}
} catch (err: any) {
console.error("Failed to fetch tag config:", err);
setError("加载标签配置时出错");
} finally {
setLoading(false);
}
};
if (loading) {
return (
<Select
placeholder="加载中..."
style={style}
disabled
suffixIcon={<Spin size="small" />}
/>
);
}
if (error) {
return (
<Tooltip title={error}>
<Select
placeholder="加载失败,点击重试"
style={style}
disabled={disabled}
status="error"
onClick={() => fetchTagConfig()}
/>
</Tooltip>
);
}
// Group controls by usage pattern
if (type === "control") {
const groups = getControlGroups();
const groupedOptions: Record<string, TagOption[]> = {};
const ungroupedOptions: TagOption[] = [];
// Group the controls
Object.entries(groups).forEach(([groupKey, groupConfig]) => {
groupedOptions[groupKey] = tagOptions.filter((opt) =>
groupConfig.controls.includes(opt.value)
);
});
// Find ungrouped controls
const allGroupedControls = new Set(
Object.values(groups).flatMap((g) => g.controls)
);
tagOptions.forEach((opt) => {
if (!allGroupedControls.has(opt.value)) {
ungroupedOptions.push(opt);
}
});
return (
<Select
value={value}
onChange={onChange}
placeholder={placeholder || "选择控件类型"}
style={style}
disabled={disabled}
showSearch
optionFilterProp="label"
>
{Object.entries(groups).map(([groupKey, groupConfig]) => {
const options = groupedOptions[groupKey];
if (options.length === 0) return null;
return (
<OptGroup key={groupKey} label={groupConfig.label}>
{options.map((opt) => (
<Option key={opt.value} value={opt.value} label={opt.label}>
<div className="flex items-center justify-between">
<span>{getControlDisplayName(opt.value)}</span>
<Tooltip title={opt.description}>
<InfoCircleOutlined
style={{ color: "#8c8c8c", fontSize: 12 }}
/>
</Tooltip>
</div>
</Option>
))}
</OptGroup>
);
})}
{ungroupedOptions.length > 0 && (
<OptGroup label="其他">
{ungroupedOptions.map((opt) => (
<Option key={opt.value} value={opt.value} label={opt.label}>
<div className="flex items-center justify-between">
<span>{getControlDisplayName(opt.value)}</span>
<Tooltip title={opt.description}>
<InfoCircleOutlined
style={{ color: "#8c8c8c", fontSize: 12 }}
/>
</Tooltip>
</div>
</Option>
))}
</OptGroup>
)}
</Select>
);
}
// Objects selector (no grouping)
return (
<Select
value={value}
onChange={onChange}
placeholder={placeholder || "选择数据对象类型"}
style={style}
disabled={disabled}
showSearch
optionFilterProp="label"
>
{tagOptions.map((opt) => (
<Option key={opt.value} value={opt.value} label={opt.label}>
<div className="flex items-center justify-between">
<span>{getObjectDisplayName(opt.value)}</span>
<Tooltip title={opt.description}>
<InfoCircleOutlined style={{ color: "#8c8c8c", fontSize: 12 }} />
</Tooltip>
</div>
</Option>
))}
</Select>
);
};
export default TagSelector;
/**
* Tag Info Panel Component
* Displays detailed information about a selected tag
*/
interface TagInfoPanelProps {
tagConfig: LabelStudioTagConfig | null;
tagType: string;
category: "object" | "control";
}
export const TagInfoPanel: React.FC<TagInfoPanelProps> = ({
tagConfig,
tagType,
category,
}) => {
if (!tagConfig || !tagType) {
return null;
}
const config =
category === "object"
? tagConfig.objects[tagType]
: tagConfig.controls[tagType];
if (!config) {
return null;
}
return (
<Collapse
size="small"
items={[
{
key: "1",
label: "标签配置详情",
children: (
<Space direction="vertical" size="small" style={{ width: "100%" }}>
<div>
<strong></strong>
{config.description}
</div>
<div>
<strong></strong>
<div style={{ marginTop: 4 }}>
{config.required_attrs.map((attr: string) => (
<Tag key={attr} color="red">
{attr}
</Tag>
))}
</div>
</div>
{config.optional_attrs &&
Object.keys(config.optional_attrs).length > 0 && (
<div>
<strong></strong>
<div style={{ marginTop: 4 }}>
{Object.entries(config.optional_attrs).map(
([attrName, attrConfig]: [string, any]) => (
<Tooltip
key={attrName}
title={
<div>
{attrConfig.description && (
<div>{attrConfig.description}</div>
)}
{attrConfig.type && (
<div>: {attrConfig.type}</div>
)}
{attrConfig.default !== undefined && (
<div>: {String(attrConfig.default)}</div>
)}
{attrConfig.values && (
<div>
: {attrConfig.values.join(", ")}
</div>
)}
</div>
}
>
<Tag color="blue" style={{ cursor: "help" }}>
{attrName}
</Tag>
</Tooltip>
)
)}
</div>
</div>
)}
{config.requires_children && (
<div>
<strong></strong>
<Tag color="green"> &lt;{config.child_tag}&gt;</Tag>
</div>
)}
</Space>
),
},
]}
/>
);
};
import React, { useState, useEffect } from "react";
import { Select, Tooltip, Spin, Collapse, Tag, Space } from "antd";
import { InfoCircleOutlined } from "@ant-design/icons";
import { getTagConfigUsingGet } from "../../annotation.api";
import type {
LabelStudioTagConfig,
TagOption,
} from "../../annotation.tagconfig";
import {
parseTagConfig,
getControlDisplayName,
getObjectDisplayName,
getControlGroups,
} from "../../annotation.tagconfig";
const { Option, OptGroup } = Select;
interface TagSelectorProps {
value?: string;
onChange?: (value: string) => void;
type: "object" | "control";
placeholder?: string;
style?: React.CSSProperties;
disabled?: boolean;
}
/**
* Tag Selector Component
* Dynamically fetches and displays available Label Studio tags from backend config
*/
const TagSelector: React.FC<TagSelectorProps> = ({
value,
onChange,
type,
placeholder,
style,
disabled,
}) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [tagOptions, setTagOptions] = useState<TagOption[]>([]);
useEffect(() => {
fetchTagConfig();
}, []);
const fetchTagConfig = async () => {
setLoading(true);
setError(null);
try {
const response = await getTagConfigUsingGet();
if (response.code === 200 && response.data) {
const config: LabelStudioTagConfig = response.data;
const { objectOptions, controlOptions } = parseTagConfig(config);
if (type === "object") {
setTagOptions(objectOptions);
} else {
setTagOptions(controlOptions);
}
} else {
setError(response.message || "获取标签配置失败");
}
} catch (err: any) {
console.error("Failed to fetch tag config:", err);
setError("加载标签配置时出错");
} finally {
setLoading(false);
}
};
if (loading) {
return (
<Select
placeholder="加载中..."
style={style}
disabled
suffixIcon={<Spin size="small" />}
/>
);
}
if (error) {
return (
<Tooltip title={error}>
<Select
placeholder="加载失败,点击重试"
style={style}
disabled={disabled}
status="error"
onClick={() => fetchTagConfig()}
/>
</Tooltip>
);
}
// Group controls by usage pattern
if (type === "control") {
const groups = getControlGroups();
const groupedOptions: Record<string, TagOption[]> = {};
const ungroupedOptions: TagOption[] = [];
// Group the controls
Object.entries(groups).forEach(([groupKey, groupConfig]) => {
groupedOptions[groupKey] = tagOptions.filter((opt) =>
groupConfig.controls.includes(opt.value)
);
});
// Find ungrouped controls
const allGroupedControls = new Set(
Object.values(groups).flatMap((g) => g.controls)
);
tagOptions.forEach((opt) => {
if (!allGroupedControls.has(opt.value)) {
ungroupedOptions.push(opt);
}
});
return (
<Select
value={value}
onChange={onChange}
placeholder={placeholder || "选择控件类型"}
style={style}
disabled={disabled}
showSearch
optionFilterProp="label"
>
{Object.entries(groups).map(([groupKey, groupConfig]) => {
const options = groupedOptions[groupKey];
if (options.length === 0) return null;
return (
<OptGroup key={groupKey} label={groupConfig.label}>
{options.map((opt) => (
<Option key={opt.value} value={opt.value} label={opt.label}>
<div className="flex items-center justify-between">
<span>{getControlDisplayName(opt.value)}</span>
<Tooltip title={opt.description}>
<InfoCircleOutlined
style={{ color: "#8c8c8c", fontSize: 12 }}
/>
</Tooltip>
</div>
</Option>
))}
</OptGroup>
);
})}
{ungroupedOptions.length > 0 && (
<OptGroup label="其他">
{ungroupedOptions.map((opt) => (
<Option key={opt.value} value={opt.value} label={opt.label}>
<div className="flex items-center justify-between">
<span>{getControlDisplayName(opt.value)}</span>
<Tooltip title={opt.description}>
<InfoCircleOutlined
style={{ color: "#8c8c8c", fontSize: 12 }}
/>
</Tooltip>
</div>
</Option>
))}
</OptGroup>
)}
</Select>
);
}
// Objects selector (no grouping)
return (
<Select
value={value}
onChange={onChange}
placeholder={placeholder || "选择数据对象类型"}
style={style}
disabled={disabled}
showSearch
optionFilterProp="label"
>
{tagOptions.map((opt) => (
<Option key={opt.value} value={opt.value} label={opt.label}>
<div className="flex items-center justify-between">
<span>{getObjectDisplayName(opt.value)}</span>
<Tooltip title={opt.description}>
<InfoCircleOutlined style={{ color: "#8c8c8c", fontSize: 12 }} />
</Tooltip>
</div>
</Option>
))}
</Select>
);
};
export default TagSelector;
/**
* Tag Info Panel Component
* Displays detailed information about a selected tag
*/
interface TagInfoPanelProps {
tagConfig: LabelStudioTagConfig | null;
tagType: string;
category: "object" | "control";
}
export const TagInfoPanel: React.FC<TagInfoPanelProps> = ({
tagConfig,
tagType,
category,
}) => {
if (!tagConfig || !tagType) {
return null;
}
const config =
category === "object"
? tagConfig.objects[tagType]
: tagConfig.controls[tagType];
if (!config) {
return null;
}
return (
<Collapse
size="small"
items={[
{
key: "1",
label: "标签配置详情",
children: (
<Space direction="vertical" size="small" style={{ width: "100%" }}>
<div>
<strong></strong>
{config.description}
</div>
<div>
<strong></strong>
<div style={{ marginTop: 4 }}>
{config.required_attrs.map((attr: string) => (
<Tag key={attr} color="red">
{attr}
</Tag>
))}
</div>
</div>
{config.optional_attrs &&
Object.keys(config.optional_attrs).length > 0 && (
<div>
<strong></strong>
<div style={{ marginTop: 4 }}>
{Object.entries(config.optional_attrs).map(
([attrName, attrConfig]: [string, any]) => (
<Tooltip
key={attrName}
title={
<div>
{attrConfig.description && (
<div>{attrConfig.description}</div>
)}
{attrConfig.type && (
<div>: {attrConfig.type}</div>
)}
{attrConfig.default !== undefined && (
<div>: {String(attrConfig.default)}</div>
)}
{attrConfig.values && (
<div>
: {attrConfig.values.join(", ")}
</div>
)}
</div>
}
>
<Tag color="blue" style={{ cursor: "help" }}>
{attrName}
</Tag>
</Tooltip>
)
)}
</div>
</div>
)}
{config.requires_children && (
<div>
<strong></strong>
<Tag color="green"> &lt;{config.child_tag}&gt;</Tag>
</div>
)}
</Space>
),
},
]}
/>
);
};

View File

@@ -1,3 +1,3 @@
export { default as TagSelector } from "./TagSelector";
export { default as TagBrowser } from "./TagBrowser";
export { TagInfoPanel } from "./TagSelector";
export { default as TagSelector } from "./TagSelector";
export { default as TagBrowser } from "./TagBrowser";
export { TagInfoPanel } from "./TagSelector";

View File

@@ -1,4 +1,4 @@
export { default as TemplateList } from "./TemplateList";
export { default as TemplateForm } from "./TemplateForm";
export { default as TemplateDetail } from "./TemplateDetail";
export { TagBrowser, TagSelector, TagInfoPanel } from "./components";
export { default as TemplateList } from "./TemplateList";
export { default as TemplateForm } from "./TemplateForm";
export { default as TemplateDetail } from "./TemplateDetail";
export { TagBrowser, TagSelector, TagInfoPanel } from "./components";

View File

@@ -1,50 +1,50 @@
import { get, post, put, del } from "@/utils/request";
// 标注任务管理相关接口
export function queryAnnotationTasksUsingGet(params?: any) {
return get("/api/annotation/project", params);
}
export function createAnnotationTaskUsingPost(data: any) {
return post("/api/annotation/project", data);
}
export function syncAnnotationTaskUsingPost(data: any) {
return post(`/api/annotation/task/sync`, data);
}
export function deleteAnnotationTaskByIdUsingDelete(mappingId: string) {
// Backend expects mapping UUID as path parameter
return del(`/api/annotation/project/${mappingId}`);
}
export function loginAnnotationUsingGet(mappingId: string) {
return get("/api/annotation/project/${mappingId}/login");
}
// 标签配置管理
export function getTagConfigUsingGet() {
return get("/api/annotation/tags/config");
}
// 标注模板管理
export function queryAnnotationTemplatesUsingGet(params?: any) {
return get("/api/annotation/template", params);
}
export function createAnnotationTemplateUsingPost(data: any) {
return post("/api/annotation/template", data);
}
export function updateAnnotationTemplateByIdUsingPut(
templateId: string | number,
data: any
) {
return put(`/api/annotation/template/${templateId}`, data);
}
export function deleteAnnotationTemplateByIdUsingDelete(
templateId: string | number
) {
return del(`/api/annotation/template/${templateId}`);
}
import { get, post, put, del } from "@/utils/request";
// 标注任务管理相关接口
export function queryAnnotationTasksUsingGet(params?: any) {
return get("/api/annotation/project", params);
}
export function createAnnotationTaskUsingPost(data: any) {
return post("/api/annotation/project", data);
}
export function syncAnnotationTaskUsingPost(data: any) {
return post(`/api/annotation/task/sync`, data);
}
export function deleteAnnotationTaskByIdUsingDelete(mappingId: string) {
// Backend expects mapping UUID as path parameter
return del(`/api/annotation/project/${mappingId}`);
}
export function loginAnnotationUsingGet(mappingId: string) {
return get("/api/annotation/project/${mappingId}/login");
}
// 标签配置管理
export function getTagConfigUsingGet() {
return get("/api/annotation/tags/config");
}
// 标注模板管理
export function queryAnnotationTemplatesUsingGet(params?: any) {
return get("/api/annotation/template", params);
}
export function createAnnotationTemplateUsingPost(data: any) {
return post("/api/annotation/template", data);
}
export function updateAnnotationTemplateByIdUsingPut(
templateId: string | number,
data: any
) {
return put(`/api/annotation/template/${templateId}`, data);
}
export function deleteAnnotationTemplateByIdUsingDelete(
templateId: string | number
) {
return del(`/api/annotation/template/${templateId}`);
}

View File

@@ -1,140 +1,140 @@
import { StickyNote } from "lucide-react";
import {AnnotationTaskStatus, AnnotationType, Classification, DataType, TemplateType} from "./annotation.model";
import {
CheckCircleOutlined,
ClockCircleOutlined,
CloseCircleOutlined,
} from "@ant-design/icons";
export const AnnotationTaskStatusMap = {
[AnnotationTaskStatus.ACTIVE]: {
label: "活跃",
value: AnnotationTaskStatus.ACTIVE,
color: "#409f17ff",
icon: <CheckCircleOutlined />,
},
[AnnotationTaskStatus.PROCESSING]: {
label: "处理中",
value: AnnotationTaskStatus.PROCESSING,
color: "#2673e5",
icon: <ClockCircleOutlined />,
},
[AnnotationTaskStatus.INACTIVE]: {
label: "未激活",
value: AnnotationTaskStatus.INACTIVE,
color: "#4f4444ff",
icon: <CloseCircleOutlined />,
},
};
export function mapAnnotationTask(task: any) {
// Normalize labeling project id from possible backend field names
const labelingProjId = task?.labelingProjId || task?.labelingProjectId || task?.projId || task?.labeling_project_id || "";
const statsArray = task?.statistics
? [
{ label: "准确率", value: task.statistics.accuracy ?? "-" },
{ label: "平均时长", value: task.statistics.averageTime ?? "-" },
{ label: "待复核", value: task.statistics.reviewCount ?? "-" },
]
: [];
return {
...task,
id: task.id,
// provide consistent field for components
labelingProjId,
projId: labelingProjId,
name: task.name,
description: task.description || "",
datasetName: task.datasetName || task.dataset_name || "-",
createdAt: task.createdAt || task.created_at || "-",
updatedAt: task.updatedAt || task.updated_at || "-",
icon: <StickyNote />,
iconColor: "bg-blue-100",
status: {
label:
task.status === "completed"
? "已完成"
: task.status === "processing"
? "进行中"
: task.status === "skipped"
? "已跳过"
: "待开始",
color: "bg-blue-100",
},
statistics: statsArray,
};
}
export const DataTypeMap = {
[DataType.TEXT]: {
label: "文本",
value: DataType.TEXT
},
[DataType.IMAGE]: {
label: "图片",
value: DataType.IMAGE
},
[DataType.AUDIO]: {
label: "音频",
value: DataType.AUDIO
},
[DataType.VIDEO]: {
label: "视频",
value: DataType.VIDEO
},
}
export const ClassificationMap = {
[Classification.COMPUTER_VERSION]: {
label: "计算机视觉",
value: Classification.COMPUTER_VERSION
},
[Classification.NLP]: {
label: "自然语言处理",
value: Classification.NLP
},
[Classification.AUDIO]: {
label: "音频",
value: Classification.AUDIO
},
[Classification.QUALITY_CONTROL]: {
label: "质量控制",
value: Classification.QUALITY_CONTROL
},
[Classification.CUSTOM]: {
label: "自定义",
value: Classification.CUSTOM
},
}
export const AnnotationTypeMap = {
[AnnotationType.CLASSIFICATION]: {
label: "分类",
value: AnnotationType.CLASSIFICATION
},
[AnnotationType.OBJECT_DETECTION]: {
label: "目标检测",
value: AnnotationType.OBJECT_DETECTION
},
[AnnotationType.SEGMENTATION]: {
label: "分割",
value: AnnotationType.SEGMENTATION
},
[AnnotationType.NER]: {
label: "命名实体识别",
value: AnnotationType.NER
},
}
export const TemplateTypeMap = {
[TemplateType.SYSTEM]: {
label: "系统内置",
value: TemplateType.SYSTEM
},
[TemplateType.CUSTOM]: {
label: "自定义",
value: TemplateType.CUSTOM
},
import { StickyNote } from "lucide-react";
import {AnnotationTaskStatus, AnnotationType, Classification, DataType, TemplateType} from "./annotation.model";
import {
CheckCircleOutlined,
ClockCircleOutlined,
CloseCircleOutlined,
} from "@ant-design/icons";
export const AnnotationTaskStatusMap = {
[AnnotationTaskStatus.ACTIVE]: {
label: "活跃",
value: AnnotationTaskStatus.ACTIVE,
color: "#409f17ff",
icon: <CheckCircleOutlined />,
},
[AnnotationTaskStatus.PROCESSING]: {
label: "处理中",
value: AnnotationTaskStatus.PROCESSING,
color: "#2673e5",
icon: <ClockCircleOutlined />,
},
[AnnotationTaskStatus.INACTIVE]: {
label: "未激活",
value: AnnotationTaskStatus.INACTIVE,
color: "#4f4444ff",
icon: <CloseCircleOutlined />,
},
};
export function mapAnnotationTask(task: any) {
// Normalize labeling project id from possible backend field names
const labelingProjId = task?.labelingProjId || task?.labelingProjectId || task?.projId || task?.labeling_project_id || "";
const statsArray = task?.statistics
? [
{ label: "准确率", value: task.statistics.accuracy ?? "-" },
{ label: "平均时长", value: task.statistics.averageTime ?? "-" },
{ label: "待复核", value: task.statistics.reviewCount ?? "-" },
]
: [];
return {
...task,
id: task.id,
// provide consistent field for components
labelingProjId,
projId: labelingProjId,
name: task.name,
description: task.description || "",
datasetName: task.datasetName || task.dataset_name || "-",
createdAt: task.createdAt || task.created_at || "-",
updatedAt: task.updatedAt || task.updated_at || "-",
icon: <StickyNote />,
iconColor: "bg-blue-100",
status: {
label:
task.status === "completed"
? "已完成"
: task.status === "processing"
? "进行中"
: task.status === "skipped"
? "已跳过"
: "待开始",
color: "bg-blue-100",
},
statistics: statsArray,
};
}
export const DataTypeMap = {
[DataType.TEXT]: {
label: "文本",
value: DataType.TEXT
},
[DataType.IMAGE]: {
label: "图片",
value: DataType.IMAGE
},
[DataType.AUDIO]: {
label: "音频",
value: DataType.AUDIO
},
[DataType.VIDEO]: {
label: "视频",
value: DataType.VIDEO
},
}
export const ClassificationMap = {
[Classification.COMPUTER_VERSION]: {
label: "计算机视觉",
value: Classification.COMPUTER_VERSION
},
[Classification.NLP]: {
label: "自然语言处理",
value: Classification.NLP
},
[Classification.AUDIO]: {
label: "音频",
value: Classification.AUDIO
},
[Classification.QUALITY_CONTROL]: {
label: "质量控制",
value: Classification.QUALITY_CONTROL
},
[Classification.CUSTOM]: {
label: "自定义",
value: Classification.CUSTOM
},
}
export const AnnotationTypeMap = {
[AnnotationType.CLASSIFICATION]: {
label: "分类",
value: AnnotationType.CLASSIFICATION
},
[AnnotationType.OBJECT_DETECTION]: {
label: "目标检测",
value: AnnotationType.OBJECT_DETECTION
},
[AnnotationType.SEGMENTATION]: {
label: "分割",
value: AnnotationType.SEGMENTATION
},
[AnnotationType.NER]: {
label: "命名实体识别",
value: AnnotationType.NER
},
}
export const TemplateTypeMap = {
[TemplateType.SYSTEM]: {
label: "系统内置",
value: TemplateType.SYSTEM
},
[TemplateType.CUSTOM]: {
label: "自定义",
value: TemplateType.CUSTOM
},
}

View File

@@ -1,107 +1,107 @@
import type { DatasetType } from "@/pages/DataManagement/dataset.model";
export enum AnnotationTaskStatus {
ACTIVE = "active",
INACTIVE = "inactive",
PROCESSING = "processing",
COMPLETED = "completed",
SKIPPED = "skipped",
}
export interface AnnotationTask {
id: string;
name: string;
labelingProjId: string;
datasetId: string;
annotationCount: number;
description?: string;
assignedTo?: string;
progress: number;
statistics: {
accuracy: number;
averageTime: number;
reviewCount: number;
};
status: AnnotationTaskStatus;
totalDataCount: number;
type: DatasetType;
createdAt: string;
updatedAt: string;
}
// 标注模板相关类型
export interface LabelDefinition {
fromName: string;
toName: string;
type: string;
options?: string[];
labels?: string[];
required?: boolean;
description?: string;
}
export interface ObjectDefinition {
name: string;
type: string;
value: string;
}
export interface TemplateConfiguration {
labels: LabelDefinition[];
objects: ObjectDefinition[];
metadata?: Record<string, any>;
}
export interface AnnotationTemplate {
id: string;
name: string;
description?: string;
dataType: string;
labelingType: string;
configuration: TemplateConfiguration;
labelConfig?: string;
style: string;
category: string;
builtIn: boolean;
version: string;
createdAt: string;
updatedAt?: string;
}
export interface AnnotationTemplateListResponse {
content: AnnotationTemplate[];
total: number;
page: number;
size: number;
totalPages: number;
}
export enum DataType {
TEXT = "text",
IMAGE = "image",
AUDIO = "audio",
VIDEO = "video",
}
export enum Classification {
COMPUTER_VERSION = "computer-vision",
NLP = "nlp",
AUDIO = "audio",
QUALITY_CONTROL = "quality-control",
CUSTOM = "custom"
}
export enum AnnotationType {
CLASSIFICATION = "classification",
OBJECT_DETECTION = "object-detection",
SEGMENTATION = "segmentation",
NER = "ner"
}
export enum TemplateType {
SYSTEM = "true",
CUSTOM = "false"
}
import type { DatasetType } from "@/pages/DataManagement/dataset.model";
export enum AnnotationTaskStatus {
ACTIVE = "active",
INACTIVE = "inactive",
PROCESSING = "processing",
COMPLETED = "completed",
SKIPPED = "skipped",
}
export interface AnnotationTask {
id: string;
name: string;
labelingProjId: string;
datasetId: string;
annotationCount: number;
description?: string;
assignedTo?: string;
progress: number;
statistics: {
accuracy: number;
averageTime: number;
reviewCount: number;
};
status: AnnotationTaskStatus;
totalDataCount: number;
type: DatasetType;
createdAt: string;
updatedAt: string;
}
// 标注模板相关类型
export interface LabelDefinition {
fromName: string;
toName: string;
type: string;
options?: string[];
labels?: string[];
required?: boolean;
description?: string;
}
export interface ObjectDefinition {
name: string;
type: string;
value: string;
}
export interface TemplateConfiguration {
labels: LabelDefinition[];
objects: ObjectDefinition[];
metadata?: Record<string, any>;
}
export interface AnnotationTemplate {
id: string;
name: string;
description?: string;
dataType: string;
labelingType: string;
configuration: TemplateConfiguration;
labelConfig?: string;
style: string;
category: string;
builtIn: boolean;
version: string;
createdAt: string;
updatedAt?: string;
}
export interface AnnotationTemplateListResponse {
content: AnnotationTemplate[];
total: number;
page: number;
size: number;
totalPages: number;
}
export enum DataType {
TEXT = "text",
IMAGE = "image",
AUDIO = "audio",
VIDEO = "video",
}
export enum Classification {
COMPUTER_VERSION = "computer-vision",
NLP = "nlp",
AUDIO = "audio",
QUALITY_CONTROL = "quality-control",
CUSTOM = "custom"
}
export enum AnnotationType {
CLASSIFICATION = "classification",
OBJECT_DETECTION = "object-detection",
SEGMENTATION = "segmentation",
NER = "ner"
}
export enum TemplateType {
SYSTEM = "true",
CUSTOM = "false"
}

View File

@@ -1,187 +1,187 @@
/**
* Label Studio Tag Configuration Types
* Corresponds to runtime/datamate-python/app/module/annotation/config/label_studio_tags.yaml
*/
export interface TagAttributeConfig {
type?: "boolean" | "number" | "string";
values?: string[];
default?: any;
description?: string;
}
export interface TagConfig {
description: string;
required_attrs: string[];
optional_attrs?: Record<string, TagAttributeConfig>;
requires_children?: boolean;
child_tag?: string;
child_required_attrs?: string[];
category?: string; // e.g., "labeling" or "layout" for controls; "image", "text", etc. for objects
}
export interface LabelStudioTagConfig {
objects: Record<string, TagConfig>;
controls: Record<string, TagConfig>;
}
/**
* UI-friendly representation of a tag for selection
*/
export interface TagOption {
value: string;
label: string;
description: string;
category: "object" | "control";
requiresChildren: boolean;
childTag?: string;
requiredAttrs: string[];
optionalAttrs?: Record<string, TagAttributeConfig>;
}
/**
* Convert backend tag config to frontend tag options
* @param config - The full tag configuration from backend
* @param includeLabelingOnly - If true, only include controls with category="labeling" (default: true)
*/
export function parseTagConfig(
config: LabelStudioTagConfig,
includeLabelingOnly: boolean = true
): {
objectOptions: TagOption[];
controlOptions: TagOption[];
} {
const objectOptions: TagOption[] = Object.entries(config.objects).map(
([key, value]) => ({
value: key,
label: key,
description: value.description,
category: "object" as const,
requiresChildren: value.requires_children || false,
childTag: value.child_tag,
requiredAttrs: value.required_attrs,
optionalAttrs: value.optional_attrs,
})
);
const controlOptions: TagOption[] = Object.entries(config.controls)
.filter(([_, value]) => {
// If includeLabelingOnly is true, filter out layout controls
if (includeLabelingOnly) {
return value.category === "labeling";
}
return true;
})
.map(([key, value]) => ({
value: key,
label: key,
description: value.description,
category: "control" as const,
requiresChildren: value.requires_children || false,
childTag: value.child_tag,
requiredAttrs: value.required_attrs,
optionalAttrs: value.optional_attrs,
}));
return { objectOptions, controlOptions };
}
/**
* Get user-friendly display name for control types
*/
export function getControlDisplayName(controlType: string): string {
const displayNames: Record<string, string> = {
Choices: "选项 (单选/多选)",
RectangleLabels: "矩形框",
PolygonLabels: "多边形",
Labels: "标签",
TextArea: "文本区域",
Rating: "评分",
Taxonomy: "分类树",
Ranker: "排序",
List: "列表",
BrushLabels: "画笔分割",
EllipseLabels: "椭圆",
KeyPointLabels: "关键点",
Rectangle: "矩形",
Polygon: "多边形",
Ellipse: "椭圆",
KeyPoint: "关键点",
Brush: "画笔",
Number: "数字输入",
DateTime: "日期时间",
Relation: "关系",
Relations: "关系组",
Pairwise: "成对比较",
};
return displayNames[controlType] || controlType;
}
/**
* Get user-friendly display name for object types
*/
export function getObjectDisplayName(objectType: string): string {
const displayNames: Record<string, string> = {
Image: "图像",
Text: "文本",
Audio: "音频",
Video: "视频",
HyperText: "HTML内容",
PDF: "PDF文档",
Markdown: "Markdown内容",
Paragraphs: "段落",
Table: "表格",
AudioPlus: "高级音频",
Timeseries: "时间序列",
Vector: "向量数据",
Chat: "对话数据",
};
return displayNames[objectType] || objectType;
}
/**
* Group control types by common usage patterns
*/
export function getControlGroups(): Record<
string,
{ label: string; controls: string[] }
> {
return {
classification: {
label: "分类标注",
controls: ["Choices", "Taxonomy", "Labels", "Rating"],
},
detection: {
label: "目标检测",
controls: [
"RectangleLabels",
"PolygonLabels",
"EllipseLabels",
"KeyPointLabels",
"Rectangle",
"Polygon",
"Ellipse",
"KeyPoint",
],
},
segmentation: {
label: "分割标注",
controls: ["BrushLabels", "Brush", "BitmaskLabels", "MagicWand"],
},
text: {
label: "文本输入",
controls: ["TextArea", "Number", "DateTime"],
},
other: {
label: "其他",
controls: [
"TimeseriesLabels",
"VectorLabels",
"ParagraphLabels",
"VideoRectangle",
],
},
};
}
/**
* Label Studio Tag Configuration Types
* Corresponds to runtime/datamate-python/app/module/annotation/config/label_studio_tags.yaml
*/
export interface TagAttributeConfig {
type?: "boolean" | "number" | "string";
values?: string[];
default?: any;
description?: string;
}
export interface TagConfig {
description: string;
required_attrs: string[];
optional_attrs?: Record<string, TagAttributeConfig>;
requires_children?: boolean;
child_tag?: string;
child_required_attrs?: string[];
category?: string; // e.g., "labeling" or "layout" for controls; "image", "text", etc. for objects
}
export interface LabelStudioTagConfig {
objects: Record<string, TagConfig>;
controls: Record<string, TagConfig>;
}
/**
* UI-friendly representation of a tag for selection
*/
export interface TagOption {
value: string;
label: string;
description: string;
category: "object" | "control";
requiresChildren: boolean;
childTag?: string;
requiredAttrs: string[];
optionalAttrs?: Record<string, TagAttributeConfig>;
}
/**
* Convert backend tag config to frontend tag options
* @param config - The full tag configuration from backend
* @param includeLabelingOnly - If true, only include controls with category="labeling" (default: true)
*/
export function parseTagConfig(
config: LabelStudioTagConfig,
includeLabelingOnly: boolean = true
): {
objectOptions: TagOption[];
controlOptions: TagOption[];
} {
const objectOptions: TagOption[] = Object.entries(config.objects).map(
([key, value]) => ({
value: key,
label: key,
description: value.description,
category: "object" as const,
requiresChildren: value.requires_children || false,
childTag: value.child_tag,
requiredAttrs: value.required_attrs,
optionalAttrs: value.optional_attrs,
})
);
const controlOptions: TagOption[] = Object.entries(config.controls)
.filter(([_, value]) => {
// If includeLabelingOnly is true, filter out layout controls
if (includeLabelingOnly) {
return value.category === "labeling";
}
return true;
})
.map(([key, value]) => ({
value: key,
label: key,
description: value.description,
category: "control" as const,
requiresChildren: value.requires_children || false,
childTag: value.child_tag,
requiredAttrs: value.required_attrs,
optionalAttrs: value.optional_attrs,
}));
return { objectOptions, controlOptions };
}
/**
* Get user-friendly display name for control types
*/
export function getControlDisplayName(controlType: string): string {
const displayNames: Record<string, string> = {
Choices: "选项 (单选/多选)",
RectangleLabels: "矩形框",
PolygonLabels: "多边形",
Labels: "标签",
TextArea: "文本区域",
Rating: "评分",
Taxonomy: "分类树",
Ranker: "排序",
List: "列表",
BrushLabels: "画笔分割",
EllipseLabels: "椭圆",
KeyPointLabels: "关键点",
Rectangle: "矩形",
Polygon: "多边形",
Ellipse: "椭圆",
KeyPoint: "关键点",
Brush: "画笔",
Number: "数字输入",
DateTime: "日期时间",
Relation: "关系",
Relations: "关系组",
Pairwise: "成对比较",
};
return displayNames[controlType] || controlType;
}
/**
* Get user-friendly display name for object types
*/
export function getObjectDisplayName(objectType: string): string {
const displayNames: Record<string, string> = {
Image: "图像",
Text: "文本",
Audio: "音频",
Video: "视频",
HyperText: "HTML内容",
PDF: "PDF文档",
Markdown: "Markdown内容",
Paragraphs: "段落",
Table: "表格",
AudioPlus: "高级音频",
Timeseries: "时间序列",
Vector: "向量数据",
Chat: "对话数据",
};
return displayNames[objectType] || objectType;
}
/**
* Group control types by common usage patterns
*/
export function getControlGroups(): Record<
string,
{ label: string; controls: string[] }
> {
return {
classification: {
label: "分类标注",
controls: ["Choices", "Taxonomy", "Labels", "Rating"],
},
detection: {
label: "目标检测",
controls: [
"RectangleLabels",
"PolygonLabels",
"EllipseLabels",
"KeyPointLabels",
"Rectangle",
"Polygon",
"Ellipse",
"KeyPoint",
],
},
segmentation: {
label: "分割标注",
controls: ["BrushLabels", "Brush", "BitmaskLabels", "MagicWand"],
},
text: {
label: "文本输入",
controls: ["TextArea", "Number", "DateTime"],
},
other: {
label: "其他",
controls: [
"TimeseriesLabels",
"VectorLabels",
"ParagraphLabels",
"VideoRectangle",
],
},
};
}

View File

@@ -1,133 +1,133 @@
import { useState } from "react";
import { Steps, Button, message, Form } from "antd";
import { SaveOutlined } from "@ant-design/icons";
import { Link, useNavigate } from "react-router";
import { ArrowLeft } from "lucide-react";
import { createCleaningTaskUsingPost } from "../cleansing.api";
import CreateTaskStepOne from "./components/CreateTaskStepOne";
import { useCreateStepTwo } from "./hooks/useCreateStepTwo";
import { DatasetType } from "@/pages/DataManagement/dataset.model";
export default function CleansingTaskCreate() {
const navigate = useNavigate();
const [form] = Form.useForm();
const [taskConfig, setTaskConfig] = useState({
name: "",
description: "",
srcDatasetId: "",
srcDatasetName: "",
destDatasetName: "",
destDatasetType: DatasetType.TEXT,
type: DatasetType.TEXT,
});
const {
renderStepTwo,
selectedOperators,
currentStep,
handlePrev,
handleNext,
} = useCreateStepTwo();
const handleSave = async () => {
const task = {
...taskConfig,
instance: selectedOperators.map((item) => ({
id: item.id,
overrides: {
...item.defaultParams,
...item.overrides,
},
inputs: item.inputs,
outputs: item.outputs,
})),
};
navigate("/data/cleansing?view=task");
await createCleaningTaskUsingPost(task);
message.success("任务已创建");
};
const canProceed = () => {
switch (currentStep) {
case 1: {
const values = form.getFieldsValue();
return (
values.name &&
values.srcDatasetId &&
values.destDatasetName &&
values.destDatasetType
);
}
case 2:
return selectedOperators.length > 0;
default:
return false;
}
};
const renderStepContent = () => {
switch (currentStep) {
case 1:
return (
<CreateTaskStepOne
form={form}
taskConfig={taskConfig}
setTaskConfig={setTaskConfig}
/>
);
case 2:
return renderStepTwo;
default:
return null;
}
};
return (
<div className="h-full flex flex-col">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<Link to="/data/cleansing">
<Button type="text">
<ArrowLeft className="w-4 h-4 mr-1" />
</Button>
</Link>
<h1 className="text-xl font-bold"></h1>
</div>
<div className="w-1/2">
<Steps
size="small"
current={currentStep - 1}
items={[{ title: "基本信息" }, { title: "算子编排" }]}
/>
</div>
</div>
{/* Step Content */}
<div className="flex-overflow-auto bg-white border-card">
<div className="flex-1 overflow-auto m-6">{renderStepContent()}</div>
<div className="flex justify-end p-6 gap-3 border-top">
<Button onClick={() => navigate("/data/cleansing")}></Button>
{currentStep > 1 && <Button onClick={handlePrev}></Button>}
{currentStep === 2 ? (
<Button
type="primary"
icon={<SaveOutlined />}
onClick={handleSave}
disabled={!canProceed()}
>
</Button>
) : (
<Button
type="primary"
onClick={handleNext}
disabled={!canProceed()}
>
</Button>
)}
</div>
</div>
</div>
);
}
import { useState } from "react";
import { Steps, Button, message, Form } from "antd";
import { SaveOutlined } from "@ant-design/icons";
import { Link, useNavigate } from "react-router";
import { ArrowLeft } from "lucide-react";
import { createCleaningTaskUsingPost } from "../cleansing.api";
import CreateTaskStepOne from "./components/CreateTaskStepOne";
import { useCreateStepTwo } from "./hooks/useCreateStepTwo";
import { DatasetType } from "@/pages/DataManagement/dataset.model";
export default function CleansingTaskCreate() {
const navigate = useNavigate();
const [form] = Form.useForm();
const [taskConfig, setTaskConfig] = useState({
name: "",
description: "",
srcDatasetId: "",
srcDatasetName: "",
destDatasetName: "",
destDatasetType: DatasetType.TEXT,
type: DatasetType.TEXT,
});
const {
renderStepTwo,
selectedOperators,
currentStep,
handlePrev,
handleNext,
} = useCreateStepTwo();
const handleSave = async () => {
const task = {
...taskConfig,
instance: selectedOperators.map((item) => ({
id: item.id,
overrides: {
...item.defaultParams,
...item.overrides,
},
inputs: item.inputs,
outputs: item.outputs,
})),
};
navigate("/data/cleansing?view=task");
await createCleaningTaskUsingPost(task);
message.success("任务已创建");
};
const canProceed = () => {
switch (currentStep) {
case 1: {
const values = form.getFieldsValue();
return (
values.name &&
values.srcDatasetId &&
values.destDatasetName &&
values.destDatasetType
);
}
case 2:
return selectedOperators.length > 0;
default:
return false;
}
};
const renderStepContent = () => {
switch (currentStep) {
case 1:
return (
<CreateTaskStepOne
form={form}
taskConfig={taskConfig}
setTaskConfig={setTaskConfig}
/>
);
case 2:
return renderStepTwo;
default:
return null;
}
};
return (
<div className="h-full flex flex-col">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<Link to="/data/cleansing">
<Button type="text">
<ArrowLeft className="w-4 h-4 mr-1" />
</Button>
</Link>
<h1 className="text-xl font-bold"></h1>
</div>
<div className="w-1/2">
<Steps
size="small"
current={currentStep - 1}
items={[{ title: "基本信息" }, { title: "算子编排" }]}
/>
</div>
</div>
{/* Step Content */}
<div className="flex-overflow-auto bg-white border-card">
<div className="flex-1 overflow-auto m-6">{renderStepContent()}</div>
<div className="flex justify-end p-6 gap-3 border-top">
<Button onClick={() => navigate("/data/cleansing")}></Button>
{currentStep > 1 && <Button onClick={handlePrev}></Button>}
{currentStep === 2 ? (
<Button
type="primary"
icon={<SaveOutlined />}
onClick={handleSave}
disabled={!canProceed()}
>
</Button>
) : (
<Button
type="primary"
onClick={handleNext}
disabled={!canProceed()}
>
</Button>
)}
</div>
</div>
</div>
);
}

View File

@@ -1,142 +1,142 @@
import {useEffect, useState} from "react";
import {Button, Steps, Form, message} from "antd";
import {Link, useNavigate, useParams} from "react-router";
import { ArrowLeft } from "lucide-react";
import {
createCleaningTemplateUsingPost,
queryCleaningTemplateByIdUsingGet,
updateCleaningTemplateByIdUsingPut
} from "../cleansing.api";
import CleansingTemplateStepOne from "./components/CreateTemplateStepOne";
import { useCreateStepTwo } from "./hooks/useCreateStepTwo";
export default function CleansingTemplateCreate() {
const { id = "" } = useParams()
const navigate = useNavigate();
const [form] = Form.useForm();
const [templateConfig, setTemplateConfig] = useState({
name: "",
description: "",
});
const fetchTemplateDetail = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTemplateByIdUsingGet(id);
setTemplateConfig(data);
} catch (error) {
message.error("获取任务详情失败");
navigate("/data/cleansing");
}
};
useEffect(() => {
fetchTemplateDetail()
}, [id]);
const handleSave = async () => {
const template = {
...templateConfig,
instance: selectedOperators.map((item) => ({
id: item.id,
overrides: {
...item.defaultParams,
...item.overrides,
},
inputs: item.inputs,
outputs: item.outputs,
})),
};
!id && await createCleaningTemplateUsingPost(template) && message.success("模板创建成功");
id && await updateCleaningTemplateByIdUsingPut(id, template) && message.success("模板更新成功");
navigate("/data/cleansing?view=template");
};
const {
renderStepTwo,
selectedOperators,
currentStep,
handlePrev,
handleNext,
} = useCreateStepTwo();
const canProceed = () => {
const values = form.getFieldsValue();
switch (currentStep) {
case 1:
return values.name;
case 2:
return selectedOperators.length > 0;
default:
return false;
}
};
const renderStepContent = () => {
switch (currentStep) {
case 1:
return (
<CleansingTemplateStepOne
form={form}
templateConfig={templateConfig}
setTemplateConfig={setTemplateConfig}
/>
);
case 2:
return renderStepTwo;
default:
return null;
}
};
return (
<div className="h-full flex flex-col">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<Link to="/data/cleansing">
<Button type="text">
<ArrowLeft className="w-4 h-4 mr-1" />
</Button>
</Link>
<h1 className="text-xl font-bold">{id ? '更新清洗模板' : '创建清洗模板'}</h1>
</div>
<div className="w-1/2">
<Steps
size="small"
current={currentStep}
items={[{ title: "基本信息" }, { title: "算子编排" }]}
/>
</div>
</div>
<div className="flex-overflow-auto border-card">
<div className="flex-1 overflow-auto m-6">{renderStepContent()}</div>
<div className="flex justify-end p-6 gap-3 border-top">
<Button onClick={() => navigate("/data/cleansing")}></Button>
{currentStep > 1 && <Button onClick={handlePrev}></Button>}
{currentStep === 2 ? (
<Button
type="primary"
onClick={handleSave}
disabled={!canProceed()}
>
{id ? '更新模板' : '创建模板'}
</Button>
) : (
<Button
type="primary"
onClick={handleNext}
disabled={!canProceed()}
>
</Button>
)}
</div>
</div>
</div>
);
}
import {useEffect, useState} from "react";
import {Button, Steps, Form, message} from "antd";
import {Link, useNavigate, useParams} from "react-router";
import { ArrowLeft } from "lucide-react";
import {
createCleaningTemplateUsingPost,
queryCleaningTemplateByIdUsingGet,
updateCleaningTemplateByIdUsingPut
} from "../cleansing.api";
import CleansingTemplateStepOne from "./components/CreateTemplateStepOne";
import { useCreateStepTwo } from "./hooks/useCreateStepTwo";
export default function CleansingTemplateCreate() {
const { id = "" } = useParams()
const navigate = useNavigate();
const [form] = Form.useForm();
const [templateConfig, setTemplateConfig] = useState({
name: "",
description: "",
});
const fetchTemplateDetail = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTemplateByIdUsingGet(id);
setTemplateConfig(data);
} catch (error) {
message.error("获取任务详情失败");
navigate("/data/cleansing");
}
};
useEffect(() => {
fetchTemplateDetail()
}, [id]);
const handleSave = async () => {
const template = {
...templateConfig,
instance: selectedOperators.map((item) => ({
id: item.id,
overrides: {
...item.defaultParams,
...item.overrides,
},
inputs: item.inputs,
outputs: item.outputs,
})),
};
!id && await createCleaningTemplateUsingPost(template) && message.success("模板创建成功");
id && await updateCleaningTemplateByIdUsingPut(id, template) && message.success("模板更新成功");
navigate("/data/cleansing?view=template");
};
const {
renderStepTwo,
selectedOperators,
currentStep,
handlePrev,
handleNext,
} = useCreateStepTwo();
const canProceed = () => {
const values = form.getFieldsValue();
switch (currentStep) {
case 1:
return values.name;
case 2:
return selectedOperators.length > 0;
default:
return false;
}
};
const renderStepContent = () => {
switch (currentStep) {
case 1:
return (
<CleansingTemplateStepOne
form={form}
templateConfig={templateConfig}
setTemplateConfig={setTemplateConfig}
/>
);
case 2:
return renderStepTwo;
default:
return null;
}
};
return (
<div className="h-full flex flex-col">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<Link to="/data/cleansing">
<Button type="text">
<ArrowLeft className="w-4 h-4 mr-1" />
</Button>
</Link>
<h1 className="text-xl font-bold">{id ? '更新清洗模板' : '创建清洗模板'}</h1>
</div>
<div className="w-1/2">
<Steps
size="small"
current={currentStep}
items={[{ title: "基本信息" }, { title: "算子编排" }]}
/>
</div>
</div>
<div className="flex-overflow-auto border-card">
<div className="flex-1 overflow-auto m-6">{renderStepContent()}</div>
<div className="flex justify-end p-6 gap-3 border-top">
<Button onClick={() => navigate("/data/cleansing")}></Button>
{currentStep > 1 && <Button onClick={handlePrev}></Button>}
{currentStep === 2 ? (
<Button
type="primary"
onClick={handleSave}
disabled={!canProceed()}
>
{id ? '更新模板' : '创建模板'}
</Button>
) : (
<Button
type="primary"
onClick={handleNext}
disabled={!canProceed()}
>
</Button>
)}
</div>
</div>
</div>
);
}

View File

@@ -1,113 +1,113 @@
import RadioCard from "@/components/RadioCard";
import { queryDatasetsUsingGet } from "@/pages/DataManagement/dataset.api";
import { datasetTypes, mapDataset } from "@/pages/DataManagement/dataset.const";
import {
Dataset,
DatasetSubType,
DatasetType,
} from "@/pages/DataManagement/dataset.model";
import { Input, Select, Form } from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
export default function CreateTaskStepOne({
form,
taskConfig,
setTaskConfig,
}: {
form: any;
taskConfig: {
name: string;
description: string;
datasetId: string;
destDatasetName: string;
type: DatasetType;
destDatasetType: DatasetSubType;
};
setTaskConfig: (config: any) => void;
}) {
const [datasets, setDatasets] = useState<Dataset[]>([]);
const fetchDatasets = async () => {
const { data } = await queryDatasetsUsingGet({ page: 1, size: 1000 });
setDatasets(data.content.map(mapDataset) || []);
};
useEffect(() => {
fetchDatasets();
}, []);
const handleValuesChange = (currentValue, allValues) => {
const [key, value] = Object.entries(currentValue)[0];
let dataset = null;
if (key === "srcDatasetId") {
dataset = datasets.find((d) => d.id === value);
setTaskConfig({
...taskConfig,
...allValues,
srcDatasetName: dataset?.name || "",
});
} else {
setTaskConfig({ ...taskConfig, ...allValues });
}
};
return (
<Form
layout="vertical"
form={form}
initialValues={taskConfig}
onValuesChange={handleValuesChange}
>
<h2 className="font-medium text-gray-900 text-base mb-2"></h2>
<Form.Item label="名称" name="name" required>
<Input placeholder="输入清洗任务名称" />
</Form.Item>
<Form.Item label="描述" name="description">
<TextArea placeholder="描述清洗任务的目标和要求" rows={4} />
</Form.Item>
<h2 className="font-medium text-gray-900 pt-6 mb-2 text-base">
</h2>
<Form.Item label="源数据集" name="srcDatasetId" required>
<Select
placeholder="请选择源数据集"
options={datasets.map((dataset) => {
return {
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="flex items-center font-sm text-gray-900">
<span className="mr-2">{dataset.icon}</span>
<span>{dataset.name}</span>
</div>
<div className="text-xs text-gray-500">{dataset.size}</div>
</div>
),
value: dataset.id,
};
})}
/>
</Form.Item>
<Form.Item label="目标数据集名称" name="destDatasetName" required>
<Input placeholder="输入目标数据集名称" />
</Form.Item>
<Form.Item
label="目标数据集类型"
name="destDatasetType"
rules={[{ required: true, message: "请选择目标数据集类型" }]}
>
<RadioCard
options={datasetTypes}
value={taskConfig.destDatasetType}
onChange={(type) => {
form.setFieldValue("destDatasetType", type);
setTaskConfig({
...taskConfig,
destDatasetType: type as DatasetSubType,
});
}}
/>
</Form.Item>
</Form>
);
}
import RadioCard from "@/components/RadioCard";
import { queryDatasetsUsingGet } from "@/pages/DataManagement/dataset.api";
import { datasetTypes, mapDataset } from "@/pages/DataManagement/dataset.const";
import {
Dataset,
DatasetSubType,
DatasetType,
} from "@/pages/DataManagement/dataset.model";
import { Input, Select, Form } from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
export default function CreateTaskStepOne({
form,
taskConfig,
setTaskConfig,
}: {
form: any;
taskConfig: {
name: string;
description: string;
datasetId: string;
destDatasetName: string;
type: DatasetType;
destDatasetType: DatasetSubType;
};
setTaskConfig: (config: any) => void;
}) {
const [datasets, setDatasets] = useState<Dataset[]>([]);
const fetchDatasets = async () => {
const { data } = await queryDatasetsUsingGet({ page: 1, size: 1000 });
setDatasets(data.content.map(mapDataset) || []);
};
useEffect(() => {
fetchDatasets();
}, []);
const handleValuesChange = (currentValue, allValues) => {
const [key, value] = Object.entries(currentValue)[0];
let dataset = null;
if (key === "srcDatasetId") {
dataset = datasets.find((d) => d.id === value);
setTaskConfig({
...taskConfig,
...allValues,
srcDatasetName: dataset?.name || "",
});
} else {
setTaskConfig({ ...taskConfig, ...allValues });
}
};
return (
<Form
layout="vertical"
form={form}
initialValues={taskConfig}
onValuesChange={handleValuesChange}
>
<h2 className="font-medium text-gray-900 text-base mb-2"></h2>
<Form.Item label="名称" name="name" required>
<Input placeholder="输入清洗任务名称" />
</Form.Item>
<Form.Item label="描述" name="description">
<TextArea placeholder="描述清洗任务的目标和要求" rows={4} />
</Form.Item>
<h2 className="font-medium text-gray-900 pt-6 mb-2 text-base">
</h2>
<Form.Item label="源数据集" name="srcDatasetId" required>
<Select
placeholder="请选择源数据集"
options={datasets.map((dataset) => {
return {
label: (
<div className="flex items-center justify-between gap-3 py-2">
<div className="flex items-center font-sm text-gray-900">
<span className="mr-2">{dataset.icon}</span>
<span>{dataset.name}</span>
</div>
<div className="text-xs text-gray-500">{dataset.size}</div>
</div>
),
value: dataset.id,
};
})}
/>
</Form.Item>
<Form.Item label="目标数据集名称" name="destDatasetName" required>
<Input placeholder="输入目标数据集名称" />
</Form.Item>
<Form.Item
label="目标数据集类型"
name="destDatasetType"
rules={[{ required: true, message: "请选择目标数据集类型" }]}
>
<RadioCard
options={datasetTypes}
value={taskConfig.destDatasetType}
onChange={(type) => {
form.setFieldValue("destDatasetType", type);
setTaskConfig({
...taskConfig,
destDatasetType: type as DatasetSubType,
});
}}
/>
</Form.Item>
</Form>
);
}

View File

@@ -1,44 +1,44 @@
import { Input, Form } from "antd";
import {useEffect} from "react";
const { TextArea } = Input;
export default function CreateTemplateStepOne({
form,
templateConfig,
setTemplateConfig,
}: {
form: any;
templateConfig: { name: string; description: string; type: string };
setTemplateConfig: React.Dispatch<
React.SetStateAction<{ name: string; description: string; type: string }>
>;
}) {
const handleValuesChange = (_, allValues) => {
setTemplateConfig({ ...templateConfig, ...allValues });
};
useEffect(() => {
form.setFieldsValue(templateConfig);
}, [templateConfig]);
return (
<Form
form={form}
layout="vertical"
initialValues={templateConfig}
onValuesChange={handleValuesChange}
>
<Form.Item
label="模板名称"
name="name"
rules={[{ required: true, message: "请输入模板名称" }]}
>
<Input placeholder="输入模板名称" />
</Form.Item>
<Form.Item label="模板描述" name="description">
<TextArea placeholder="描述模板的用途和特点" rows={4} />
</Form.Item>
</Form>
);
}
import { Input, Form } from "antd";
import {useEffect} from "react";
const { TextArea } = Input;
export default function CreateTemplateStepOne({
form,
templateConfig,
setTemplateConfig,
}: {
form: any;
templateConfig: { name: string; description: string; type: string };
setTemplateConfig: React.Dispatch<
React.SetStateAction<{ name: string; description: string; type: string }>
>;
}) {
const handleValuesChange = (_, allValues) => {
setTemplateConfig({ ...templateConfig, ...allValues });
};
useEffect(() => {
form.setFieldsValue(templateConfig);
}, [templateConfig]);
return (
<Form
form={form}
layout="vertical"
initialValues={templateConfig}
onValuesChange={handleValuesChange}
>
<Form.Item
label="模板名称"
name="name"
rules={[{ required: true, message: "请输入模板名称" }]}
>
<Input placeholder="输入模板名称" />
</Form.Item>
<Form.Item label="模板描述" name="description">
<TextArea placeholder="描述模板的用途和特点" rows={4} />
</Form.Item>
</Form>
);
}

View File

@@ -1,81 +1,81 @@
import React from "react";
import { Tag, Divider, Form } from "antd";
import ParamConfig from "./ParamConfig";
import { Settings } from "lucide-react";
import { OperatorI } from "@/pages/OperatorMarket/operator.model";
// OperatorConfig/OperatorTemplate 类型需根据主文件实际导入
interface OperatorConfigProps {
selectedOp: OperatorI;
renderParamConfig?: (
operator: OperatorI,
paramKey: string,
param: any
) => React.ReactNode;
handleConfigChange?: (
operatorId: string,
paramKey: string,
value: any
) => void;
}
const OperatorConfig: React.FC<OperatorConfigProps> = ({
selectedOp,
renderParamConfig,
handleConfigChange,
}) => {
return (
<div className="w-1/4 min-w-3xs flex flex-col h-full">
<div className="px-4 pb-4 border-b border-gray-200">
<span className="font-semibold text-base flex items-center gap-2">
<Settings />
</span>
</div>
<div className="flex-1 overflow-auto p-4">
{selectedOp ? (
<div>
<div className="mb-4">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium">{selectedOp.name}</span>
</div>
<div className="text-sm text-gray-500">
{selectedOp.description}
</div>
<div className="flex flex-wrap gap-1 mt-2">
{selectedOp?.tags?.map((tag: string) => (
<Tag key={tag} color="default">
{tag}
</Tag>
))}
</div>
</div>
<Divider />
<Form layout="vertical">
{Object.entries(selectedOp.configs).map(([key, param]) =>
renderParamConfig ? (
renderParamConfig(selectedOp, key, param)
) : (
<ParamConfig
key={key}
operator={selectedOp}
paramKey={key}
param={param}
onParamChange={handleConfigChange}
/>
)
)}
</Form>
</div>
) : (
<div className="text-center py-12 text-gray-400">
<Settings className="w-full w-10 h-10 mb-4 opacity-50" />
<div></div>
</div>
)}
</div>
</div>
);
};
export default OperatorConfig;
import React from "react";
import { Tag, Divider, Form } from "antd";
import ParamConfig from "./ParamConfig";
import { Settings } from "lucide-react";
import { OperatorI } from "@/pages/OperatorMarket/operator.model";
// OperatorConfig/OperatorTemplate 类型需根据主文件实际导入
interface OperatorConfigProps {
selectedOp: OperatorI;
renderParamConfig?: (
operator: OperatorI,
paramKey: string,
param: any
) => React.ReactNode;
handleConfigChange?: (
operatorId: string,
paramKey: string,
value: any
) => void;
}
const OperatorConfig: React.FC<OperatorConfigProps> = ({
selectedOp,
renderParamConfig,
handleConfigChange,
}) => {
return (
<div className="w-1/4 min-w-3xs flex flex-col h-full">
<div className="px-4 pb-4 border-b border-gray-200">
<span className="font-semibold text-base flex items-center gap-2">
<Settings />
</span>
</div>
<div className="flex-1 overflow-auto p-4">
{selectedOp ? (
<div>
<div className="mb-4">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium">{selectedOp.name}</span>
</div>
<div className="text-sm text-gray-500">
{selectedOp.description}
</div>
<div className="flex flex-wrap gap-1 mt-2">
{selectedOp?.tags?.map((tag: string) => (
<Tag key={tag} color="default">
{tag}
</Tag>
))}
</div>
</div>
<Divider />
<Form layout="vertical">
{Object.entries(selectedOp.configs).map(([key, param]) =>
renderParamConfig ? (
renderParamConfig(selectedOp, key, param)
) : (
<ParamConfig
key={key}
operator={selectedOp}
paramKey={key}
param={param}
onParamChange={handleConfigChange}
/>
)
)}
</Form>
</div>
) : (
<div className="text-center py-12 text-gray-400">
<Settings className="w-full w-10 h-10 mb-4 opacity-50" />
<div></div>
</div>
)}
</div>
</div>
);
};
export default OperatorConfig;

View File

@@ -1,287 +1,287 @@
import React, {useEffect, useMemo, useState} from "react";
import {Button, Card, Checkbox, Collapse, Input, Select, Tag, Tooltip,} from "antd";
import {SearchOutlined, StarFilled, StarOutlined} from "@ant-design/icons";
import {CategoryI, OperatorI} from "@/pages/OperatorMarket/operator.model";
import {Layers} from "lucide-react";
import {updateOperatorByIdUsingPut} from "@/pages/OperatorMarket/operator.api.ts";
interface OperatorListProps {
operators: OperatorI[];
favorites: Set<string>;
showPoppular?: boolean;
toggleFavorite: (id: string) => void;
toggleOperator: (operator: OperatorI) => void;
selectedOperators: OperatorI[];
onDragOperator: (
e: React.DragEvent,
item: OperatorI,
source: "library"
) => void;
}
const handleStar = async (operator: OperatorI, toggleFavorite: (id: string) => void) => {
const data = {
id: operator.id,
isStar: !operator.isStar
};
await updateOperatorByIdUsingPut(operator.id, data);
toggleFavorite(operator.id)
}
const OperatorList: React.FC<OperatorListProps> = ({
operators,
favorites,
toggleFavorite,
toggleOperator,
selectedOperators,
onDragOperator,
}) => (
<div className="grid grid-cols-1 gap-2">
{operators.map((operator) => {
// 判断是否已选
const isSelected = selectedOperators.some((op) => op.id === operator.id);
return (
<Card
size="small"
key={operator.id}
draggable
hoverable
onDragStart={(e) => onDragOperator(e, operator, "library")}
onClick={() => toggleOperator(operator)}
>
<div className="flex items-center justify-between">
<div className="flex flex-1 min-w-0 items-center gap-2">
<Checkbox checked={isSelected} />
<span className="flex-1 min-w-0 font-medium text-sm overflow-hidden text-ellipsis whitespace-nowrap">
{operator.name}
</span>
</div>
<span
className="cursor-pointer"
onClick={(event) => {
event.stopPropagation();
handleStar(operator, toggleFavorite);
}}
>
{favorites.has(operator.id) ? (
<StarFilled style={{ color: "#FFD700" }} />
) : (
<StarOutlined />
)}
</span>
</div>
</Card>
);
})}
</div>
);
interface OperatorLibraryProps {
selectedOperators: OperatorI[];
operatorList: OperatorI[];
categoryOptions: CategoryI[];
setSelectedOperators: (operators: OperatorI[]) => void;
toggleOperator: (template: OperatorI) => void;
handleDragStart: (
e: React.DragEvent,
item: OperatorI,
source: "library"
) => void;
}
const OperatorLibrary: React.FC<OperatorLibraryProps> = ({
selectedOperators,
operatorList,
categoryOptions,
setSelectedOperators,
toggleOperator,
handleDragStart,
}) => {
const [searchTerm, setSearchTerm] = useState("");
const [showFavorites, setShowFavorites] = useState(false);
const [favorites, setFavorites] = useState<Set<string>>(new Set());
const [selectedCategory, setSelectedCategory] = useState<string>("all");
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
new Set([])
);
// 按分类分组
const groupedOperators = useMemo(() => {
const groups: { [key: string]: OperatorI[] } = {};
categoryOptions.forEach((cat: any) => {
groups[cat.name] = {
...cat,
operators: operatorList.filter((op) => op.categories?.includes(cat.id)),
};
});
if (selectedCategory && selectedCategory !== "all") {
Object.keys(groups).forEach((key) => {
if (groups[key].id !== selectedCategory) {
delete groups[key];
}
});
}
if (searchTerm) {
Object.keys(groups).forEach((key) => {
groups[key].operators = groups[key].operators.filter((operator) =>
operator.name.toLowerCase().includes(searchTerm.toLowerCase())
);
if (groups[key].operators.length === 0) {
delete groups[key];
}
});
}
if (showFavorites) {
Object.keys(groups).forEach((key) => {
groups[key].operators = groups[key].operators.filter((operator) =>
favorites.has(operator.id)
);
if (groups[key].operators.length === 0) {
delete groups[key];
}
});
}
setExpandedCategories(new Set(Object.keys(groups)));
return groups;
}, [categoryOptions, selectedCategory, searchTerm, showFavorites]);
// 过滤算子
const filteredOperators = useMemo(() => {
return Object.values(groupedOperators).flatMap(
(category) => category.operators
);
}, [groupedOperators]);
// 收藏切换
const toggleFavorite = (operatorId: string) => {
const newFavorites = new Set(favorites);
if (newFavorites.has(operatorId)) {
newFavorites.delete(operatorId);
} else {
newFavorites.add(operatorId);
}
setFavorites(newFavorites);
};
const fetchFavorite = async () => {
const newFavorites = new Set(favorites);
operatorList.forEach(item => {
item.isStar && newFavorites.add(item.id);
});
setFavorites(newFavorites);
}
useEffect(() => {
fetchFavorite()
}, [operatorList]);
// 全选分类算子
const handleSelectAll = (operators: OperatorI[]) => {
const newSelected = [...selectedOperators];
operators.forEach((operator) => {
if (!newSelected.some((op) => op.id === operator.id)) {
newSelected.push(operator);
}
});
setSelectedOperators(newSelected);
};
return (
<div className="w-1/4 h-full min-w-3xs flex flex-col">
<div className="pb-4 border-b border-gray-200">
<span className="flex items-center font-semibold text-base">
<Layers className="w-4 h-4 mr-2" />
({filteredOperators.length})
</span>
</div>
<div className="flex flex-col h-full pt-4 pr-4 overflow-hidden">
{/* 过滤器 */}
<div className="flex flex-wrap gap-2 border-b border-gray-100 pb-4">
<Input
prefix={<SearchOutlined />}
placeholder="搜索算子名称..."
value={searchTerm}
allowClear
onChange={(e) => setSearchTerm(e.target.value)}
/>
<Select
value={selectedCategory}
options={[{ label: "全部分类", value: "all" }, ...categoryOptions]}
onChange={setSelectedCategory}
className="flex-1"
placeholder="选择分类"
></Select>
<Tooltip title="只看收藏">
<span
className="cursor-pointer"
onClick={() => setShowFavorites(!showFavorites)}
>
{showFavorites ? (
<StarFilled style={{ color: "#FFD700" }} />
) : (
<StarOutlined />
)}
</span>
</Tooltip>
</div>
{/* 算子列表 */}
<div className="flex-1 overflow-auto">
{/* 分类算子 */}
<Collapse
ghost
activeKey={Array.from(expandedCategories)}
onChange={(keys) =>
setExpandedCategories(
new Set(Array.isArray(keys) ? keys : [keys])
)
}
>
{Object.entries(groupedOperators).map(([key, category]) => (
<Collapse.Panel
key={key}
header={
<div className="flex items-center justify-between w-full">
<span className="flex items-center gap-2">
<span>{category.name}</span>
<Tag>{category.operators.length}</Tag>
</span>
<Button
type="link"
size="small"
onClick={(e) => {
e.stopPropagation();
handleSelectAll(category.operators);
}}
>
</Button>
</div>
}
>
<OperatorList
selectedOperators={selectedOperators}
operators={category.operators}
favorites={favorites}
toggleOperator={toggleOperator}
onDragOperator={handleDragStart}
toggleFavorite={toggleFavorite}
/>
</Collapse.Panel>
))}
</Collapse>
{filteredOperators.length === 0 && (
<div className="text-center py-8 text-gray-400">
<SearchOutlined className="text-3xl mb-2 opacity-50" />
<div></div>
</div>
)}
</div>
</div>
</div>
);
};
export default OperatorLibrary;
import React, {useEffect, useMemo, useState} from "react";
import {Button, Card, Checkbox, Collapse, Input, Select, Tag, Tooltip,} from "antd";
import {SearchOutlined, StarFilled, StarOutlined} from "@ant-design/icons";
import {CategoryI, OperatorI} from "@/pages/OperatorMarket/operator.model";
import {Layers} from "lucide-react";
import {updateOperatorByIdUsingPut} from "@/pages/OperatorMarket/operator.api.ts";
interface OperatorListProps {
operators: OperatorI[];
favorites: Set<string>;
showPoppular?: boolean;
toggleFavorite: (id: string) => void;
toggleOperator: (operator: OperatorI) => void;
selectedOperators: OperatorI[];
onDragOperator: (
e: React.DragEvent,
item: OperatorI,
source: "library"
) => void;
}
const handleStar = async (operator: OperatorI, toggleFavorite: (id: string) => void) => {
const data = {
id: operator.id,
isStar: !operator.isStar
};
await updateOperatorByIdUsingPut(operator.id, data);
toggleFavorite(operator.id)
}
const OperatorList: React.FC<OperatorListProps> = ({
operators,
favorites,
toggleFavorite,
toggleOperator,
selectedOperators,
onDragOperator,
}) => (
<div className="grid grid-cols-1 gap-2">
{operators.map((operator) => {
// 判断是否已选
const isSelected = selectedOperators.some((op) => op.id === operator.id);
return (
<Card
size="small"
key={operator.id}
draggable
hoverable
onDragStart={(e) => onDragOperator(e, operator, "library")}
onClick={() => toggleOperator(operator)}
>
<div className="flex items-center justify-between">
<div className="flex flex-1 min-w-0 items-center gap-2">
<Checkbox checked={isSelected} />
<span className="flex-1 min-w-0 font-medium text-sm overflow-hidden text-ellipsis whitespace-nowrap">
{operator.name}
</span>
</div>
<span
className="cursor-pointer"
onClick={(event) => {
event.stopPropagation();
handleStar(operator, toggleFavorite);
}}
>
{favorites.has(operator.id) ? (
<StarFilled style={{ color: "#FFD700" }} />
) : (
<StarOutlined />
)}
</span>
</div>
</Card>
);
})}
</div>
);
interface OperatorLibraryProps {
selectedOperators: OperatorI[];
operatorList: OperatorI[];
categoryOptions: CategoryI[];
setSelectedOperators: (operators: OperatorI[]) => void;
toggleOperator: (template: OperatorI) => void;
handleDragStart: (
e: React.DragEvent,
item: OperatorI,
source: "library"
) => void;
}
const OperatorLibrary: React.FC<OperatorLibraryProps> = ({
selectedOperators,
operatorList,
categoryOptions,
setSelectedOperators,
toggleOperator,
handleDragStart,
}) => {
const [searchTerm, setSearchTerm] = useState("");
const [showFavorites, setShowFavorites] = useState(false);
const [favorites, setFavorites] = useState<Set<string>>(new Set());
const [selectedCategory, setSelectedCategory] = useState<string>("all");
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
new Set([])
);
// 按分类分组
const groupedOperators = useMemo(() => {
const groups: { [key: string]: OperatorI[] } = {};
categoryOptions.forEach((cat: any) => {
groups[cat.name] = {
...cat,
operators: operatorList.filter((op) => op.categories?.includes(cat.id)),
};
});
if (selectedCategory && selectedCategory !== "all") {
Object.keys(groups).forEach((key) => {
if (groups[key].id !== selectedCategory) {
delete groups[key];
}
});
}
if (searchTerm) {
Object.keys(groups).forEach((key) => {
groups[key].operators = groups[key].operators.filter((operator) =>
operator.name.toLowerCase().includes(searchTerm.toLowerCase())
);
if (groups[key].operators.length === 0) {
delete groups[key];
}
});
}
if (showFavorites) {
Object.keys(groups).forEach((key) => {
groups[key].operators = groups[key].operators.filter((operator) =>
favorites.has(operator.id)
);
if (groups[key].operators.length === 0) {
delete groups[key];
}
});
}
setExpandedCategories(new Set(Object.keys(groups)));
return groups;
}, [categoryOptions, selectedCategory, searchTerm, showFavorites]);
// 过滤算子
const filteredOperators = useMemo(() => {
return Object.values(groupedOperators).flatMap(
(category) => category.operators
);
}, [groupedOperators]);
// 收藏切换
const toggleFavorite = (operatorId: string) => {
const newFavorites = new Set(favorites);
if (newFavorites.has(operatorId)) {
newFavorites.delete(operatorId);
} else {
newFavorites.add(operatorId);
}
setFavorites(newFavorites);
};
const fetchFavorite = async () => {
const newFavorites = new Set(favorites);
operatorList.forEach(item => {
item.isStar && newFavorites.add(item.id);
});
setFavorites(newFavorites);
}
useEffect(() => {
fetchFavorite()
}, [operatorList]);
// 全选分类算子
const handleSelectAll = (operators: OperatorI[]) => {
const newSelected = [...selectedOperators];
operators.forEach((operator) => {
if (!newSelected.some((op) => op.id === operator.id)) {
newSelected.push(operator);
}
});
setSelectedOperators(newSelected);
};
return (
<div className="w-1/4 h-full min-w-3xs flex flex-col">
<div className="pb-4 border-b border-gray-200">
<span className="flex items-center font-semibold text-base">
<Layers className="w-4 h-4 mr-2" />
({filteredOperators.length})
</span>
</div>
<div className="flex flex-col h-full pt-4 pr-4 overflow-hidden">
{/* 过滤器 */}
<div className="flex flex-wrap gap-2 border-b border-gray-100 pb-4">
<Input
prefix={<SearchOutlined />}
placeholder="搜索算子名称..."
value={searchTerm}
allowClear
onChange={(e) => setSearchTerm(e.target.value)}
/>
<Select
value={selectedCategory}
options={[{ label: "全部分类", value: "all" }, ...categoryOptions]}
onChange={setSelectedCategory}
className="flex-1"
placeholder="选择分类"
></Select>
<Tooltip title="只看收藏">
<span
className="cursor-pointer"
onClick={() => setShowFavorites(!showFavorites)}
>
{showFavorites ? (
<StarFilled style={{ color: "#FFD700" }} />
) : (
<StarOutlined />
)}
</span>
</Tooltip>
</div>
{/* 算子列表 */}
<div className="flex-1 overflow-auto">
{/* 分类算子 */}
<Collapse
ghost
activeKey={Array.from(expandedCategories)}
onChange={(keys) =>
setExpandedCategories(
new Set(Array.isArray(keys) ? keys : [keys])
)
}
>
{Object.entries(groupedOperators).map(([key, category]) => (
<Collapse.Panel
key={key}
header={
<div className="flex items-center justify-between w-full">
<span className="flex items-center gap-2">
<span>{category.name}</span>
<Tag>{category.operators.length}</Tag>
</span>
<Button
type="link"
size="small"
onClick={(e) => {
e.stopPropagation();
handleSelectAll(category.operators);
}}
>
</Button>
</div>
}
>
<OperatorList
selectedOperators={selectedOperators}
operators={category.operators}
favorites={favorites}
toggleOperator={toggleOperator}
onDragOperator={handleDragStart}
toggleFavorite={toggleFavorite}
/>
</Collapse.Panel>
))}
</Collapse>
{filteredOperators.length === 0 && (
<div className="text-center py-8 text-gray-400">
<SearchOutlined className="text-3xl mb-2 opacity-50" />
<div></div>
</div>
)}
</div>
</div>
</div>
);
};
export default OperatorLibrary;

View File

@@ -1,213 +1,213 @@
import React, {useMemo, useState} from "react";
import { Card, Input, Tag, Select, Button } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import { CleansingTemplate } from "../../cleansing.model";
import { Workflow } from "lucide-react";
import {CategoryI, OperatorI} from "@/pages/OperatorMarket/operator.model";
interface OperatorFlowProps {
selectedOperators: OperatorI[];
configOperator: OperatorI | null;
templates: CleansingTemplate[];
currentTemplate: CleansingTemplate | null;
categoryOptions: [];
setCurrentTemplate: (template: CleansingTemplate | null) => void;
removeOperator: (id: string) => void;
setSelectedOperators: (operators: OperatorI[]) => void;
setConfigOperator: (operator: OperatorI | null) => void;
handleDragStart: (
e: React.DragEvent,
operator: OperatorI,
source: "sort"
) => void;
handleItemDragOver: (e: React.DragEvent, itemId: string) => void;
handleItemDragLeave: (e: React.DragEvent) => void;
handleItemDrop: (e: React.DragEvent, index: number) => void;
handleContainerDragOver: (e: React.DragEvent) => void;
handleContainerDragLeave: (e: React.DragEvent) => void;
handleDragEnd: (e: React.DragEvent) => void;
handleDropToContainer: (e: React.DragEvent) => void;
}
const OperatorFlow: React.FC<OperatorFlowProps> = ({
selectedOperators,
configOperator,
templates,
currentTemplate,
categoryOptions,
setSelectedOperators,
setConfigOperator,
removeOperator,
setCurrentTemplate,
handleDragStart,
handleItemDragLeave,
handleItemDragOver,
handleItemDrop,
handleContainerDragLeave,
handleDropToContainer,
handleDragEnd,
}) => {
const [editingIndex, setEditingIndex] = useState<string | null>(null);
const categoryMap = useMemo(() => {
const map: { [key: string]: CategoryI } = {};
categoryOptions.forEach((cat: any) => {
map[cat.id] = {
...cat,
};
});
return map;
}, [categoryOptions]);
// 添加编号修改处理函数
const handleIndexChange = (operatorId: string, newIndex: string) => {
const index = Number.parseInt(newIndex);
if (isNaN(index) || index < 1 || index > selectedOperators.length) {
return; // 无效输入,不处理
}
const currentIndex = selectedOperators.findIndex(
(op) => op.id === operatorId
);
if (currentIndex === -1) return;
const targetIndex = index - 1; // 转换为0基索引
if (currentIndex === targetIndex) return; // 位置没有变化
const newOperators = [...selectedOperators];
const [movedOperator] = newOperators.splice(currentIndex, 1);
newOperators.splice(targetIndex, 0, movedOperator);
setSelectedOperators(newOperators);
setEditingIndex(null);
};
return (
<div className="w-1/2 h-full min-w-xs flex-1 flex flex-col border-x border-gray-200">
{/* 工具栏 */}
<div className="px-4 pb-2 border-b border-gray-200">
<div className="flex flex-wrap gap-2 justify-between items-start">
<span className="font-semibold text-base flex items-center gap-2">
<Workflow className="w-5 h-5" />
({selectedOperators.length}){" "}
<Button
type="link"
size="small"
onClick={() => {
setConfigOperator(null);
setSelectedOperators([]);
}}
disabled={selectedOperators.length === 0}
>
</Button>
</span>
<Select
placeholder="选择模板"
className="min-w-64"
options={templates}
value={currentTemplate?.value}
onChange={(value) =>
setCurrentTemplate(
templates.find((t) => t.value === value) || null
)
}
></Select>
</div>
</div>
{/* 编排区域 */}
<div
className="flex-overflow-auto p-4 gap-2"
onDragOver={(e) => e.preventDefault()}
onDragLeave={handleContainerDragLeave}
onDrop={handleDropToContainer}
>
{selectedOperators.map((operator, index) => (
<Card
size="small"
key={operator.id}
style={
configOperator?.id === operator.id
? { borderColor: "#1677ff" }
: {}
}
hoverable
draggable
onDragStart={(e) => handleDragStart(e, operator, "sort")}
onDragEnd={handleDragEnd}
onDragOver={(e) => handleItemDragOver(e, operator.id)}
onDragLeave={handleItemDragLeave}
onDrop={(e) => handleItemDrop(e, index)}
onClick={() => setConfigOperator(operator)}
>
<div className="flex items-center gap-1">
{/* 可编辑编号 */}
<span></span>
{editingIndex === operator.id ? (
<Input
type="number"
min={1}
max={selectedOperators.length}
defaultValue={index + 1}
className="w-10 h-6 text-xs text-center"
style={{ width: 60 }}
autoFocus
onBlur={(e) => handleIndexChange(operator.id, e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter")
handleIndexChange(
operator.id,
(e.target as HTMLInputElement).value
);
else if (e.key === "Escape") setEditingIndex(null);
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<Tag
color="default"
onClick={(e) => {
e.stopPropagation();
setEditingIndex(operator.id);
}}
>
{index + 1}
</Tag>
)}
{/* 算子图标和名称 */}
<div className="flex items-center gap-2 min-w-0 flex-1">
<span className="font-medium text-sm truncate">
{operator.name}
</span>
</div>
{operator?.categories?.map((categoryId) => {
return <Tag color="default">{categoryMap[categoryId].name}</Tag>
})}
{/* 操作按钮 */}
<span
className="cursor-pointer text-red-500"
onClick={(e) => {
e.stopPropagation();
removeOperator(operator.id);
}}
>
<DeleteOutlined />
</span>
</div>
</Card>
))}
{selectedOperators.length === 0 && (
<div className="text-center py-16 text-gray-400 border-2 border-dashed border-gray-100 rounded-lg">
<Workflow className="w-full h-10 mb-4 opacity-50" />
<div className="text-lg font-medium mb-2"></div>
<div className="text-sm">
</div>
</div>
)}
</div>
</div>
);
};
export default OperatorFlow;
import React, {useMemo, useState} from "react";
import { Card, Input, Tag, Select, Button } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import { CleansingTemplate } from "../../cleansing.model";
import { Workflow } from "lucide-react";
import {CategoryI, OperatorI} from "@/pages/OperatorMarket/operator.model";
interface OperatorFlowProps {
selectedOperators: OperatorI[];
configOperator: OperatorI | null;
templates: CleansingTemplate[];
currentTemplate: CleansingTemplate | null;
categoryOptions: [];
setCurrentTemplate: (template: CleansingTemplate | null) => void;
removeOperator: (id: string) => void;
setSelectedOperators: (operators: OperatorI[]) => void;
setConfigOperator: (operator: OperatorI | null) => void;
handleDragStart: (
e: React.DragEvent,
operator: OperatorI,
source: "sort"
) => void;
handleItemDragOver: (e: React.DragEvent, itemId: string) => void;
handleItemDragLeave: (e: React.DragEvent) => void;
handleItemDrop: (e: React.DragEvent, index: number) => void;
handleContainerDragOver: (e: React.DragEvent) => void;
handleContainerDragLeave: (e: React.DragEvent) => void;
handleDragEnd: (e: React.DragEvent) => void;
handleDropToContainer: (e: React.DragEvent) => void;
}
const OperatorFlow: React.FC<OperatorFlowProps> = ({
selectedOperators,
configOperator,
templates,
currentTemplate,
categoryOptions,
setSelectedOperators,
setConfigOperator,
removeOperator,
setCurrentTemplate,
handleDragStart,
handleItemDragLeave,
handleItemDragOver,
handleItemDrop,
handleContainerDragLeave,
handleDropToContainer,
handleDragEnd,
}) => {
const [editingIndex, setEditingIndex] = useState<string | null>(null);
const categoryMap = useMemo(() => {
const map: { [key: string]: CategoryI } = {};
categoryOptions.forEach((cat: any) => {
map[cat.id] = {
...cat,
};
});
return map;
}, [categoryOptions]);
// 添加编号修改处理函数
const handleIndexChange = (operatorId: string, newIndex: string) => {
const index = Number.parseInt(newIndex);
if (isNaN(index) || index < 1 || index > selectedOperators.length) {
return; // 无效输入,不处理
}
const currentIndex = selectedOperators.findIndex(
(op) => op.id === operatorId
);
if (currentIndex === -1) return;
const targetIndex = index - 1; // 转换为0基索引
if (currentIndex === targetIndex) return; // 位置没有变化
const newOperators = [...selectedOperators];
const [movedOperator] = newOperators.splice(currentIndex, 1);
newOperators.splice(targetIndex, 0, movedOperator);
setSelectedOperators(newOperators);
setEditingIndex(null);
};
return (
<div className="w-1/2 h-full min-w-xs flex-1 flex flex-col border-x border-gray-200">
{/* 工具栏 */}
<div className="px-4 pb-2 border-b border-gray-200">
<div className="flex flex-wrap gap-2 justify-between items-start">
<span className="font-semibold text-base flex items-center gap-2">
<Workflow className="w-5 h-5" />
({selectedOperators.length}){" "}
<Button
type="link"
size="small"
onClick={() => {
setConfigOperator(null);
setSelectedOperators([]);
}}
disabled={selectedOperators.length === 0}
>
</Button>
</span>
<Select
placeholder="选择模板"
className="min-w-64"
options={templates}
value={currentTemplate?.value}
onChange={(value) =>
setCurrentTemplate(
templates.find((t) => t.value === value) || null
)
}
></Select>
</div>
</div>
{/* 编排区域 */}
<div
className="flex-overflow-auto p-4 gap-2"
onDragOver={(e) => e.preventDefault()}
onDragLeave={handleContainerDragLeave}
onDrop={handleDropToContainer}
>
{selectedOperators.map((operator, index) => (
<Card
size="small"
key={operator.id}
style={
configOperator?.id === operator.id
? { borderColor: "#1677ff" }
: {}
}
hoverable
draggable
onDragStart={(e) => handleDragStart(e, operator, "sort")}
onDragEnd={handleDragEnd}
onDragOver={(e) => handleItemDragOver(e, operator.id)}
onDragLeave={handleItemDragLeave}
onDrop={(e) => handleItemDrop(e, index)}
onClick={() => setConfigOperator(operator)}
>
<div className="flex items-center gap-1">
{/* 可编辑编号 */}
<span></span>
{editingIndex === operator.id ? (
<Input
type="number"
min={1}
max={selectedOperators.length}
defaultValue={index + 1}
className="w-10 h-6 text-xs text-center"
style={{ width: 60 }}
autoFocus
onBlur={(e) => handleIndexChange(operator.id, e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter")
handleIndexChange(
operator.id,
(e.target as HTMLInputElement).value
);
else if (e.key === "Escape") setEditingIndex(null);
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<Tag
color="default"
onClick={(e) => {
e.stopPropagation();
setEditingIndex(operator.id);
}}
>
{index + 1}
</Tag>
)}
{/* 算子图标和名称 */}
<div className="flex items-center gap-2 min-w-0 flex-1">
<span className="font-medium text-sm truncate">
{operator.name}
</span>
</div>
{operator?.categories?.map((categoryId) => {
return <Tag color="default">{categoryMap[categoryId].name}</Tag>
})}
{/* 操作按钮 */}
<span
className="cursor-pointer text-red-500"
onClick={(e) => {
e.stopPropagation();
removeOperator(operator.id);
}}
>
<DeleteOutlined />
</span>
</div>
</Card>
))}
{selectedOperators.length === 0 && (
<div className="text-center py-16 text-gray-400 border-2 border-dashed border-gray-100 rounded-lg">
<Workflow className="w-full h-10 mb-4 opacity-50" />
<div className="text-lg font-medium mb-2"></div>
<div className="text-sm">
</div>
</div>
)}
</div>
</div>
);
};
export default OperatorFlow;

View File

@@ -1,245 +1,245 @@
import React from "react";
import {
Input,
Select,
Radio,
Checkbox,
Form,
InputNumber,
Slider,
Space,
} from "antd";
import { ConfigI, OperatorI } from "@/pages/OperatorMarket/operator.model";
interface ParamConfigProps {
operator: OperatorI;
paramKey: string;
param: ConfigI;
onParamChange?: (operatorId: string, paramKey: string, value: any) => void;
}
const ParamConfig: React.FC<ParamConfigProps> = ({
operator,
paramKey,
param,
onParamChange,
}) => {
if (!param) return null;
let defaultVal: any = param.defaultVal;
if (param.type === "range") {
defaultVal = Array.isArray(param.defaultVal)
? param.defaultVal
: [
param?.properties?.[0]?.defaultVal,
param?.properties?.[1]?.defaultVal,
];
}
const [value, setValue] = React.useState(param.value || defaultVal);
const updateValue = (newValue: any) => {
setValue(newValue);
return onParamChange && onParamChange(operator.id, paramKey, newValue);
};
switch (param.type) {
case "input":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Input
value={value}
onChange={(e) => updateValue(e.target.value)}
placeholder={`请输入${param.name}`}
className="w-full"
/>
</Form.Item>
);
case "select":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Select
value={value}
onChange={updateValue}
options={(param.options || []).map((option: any) =>
typeof option === "string"
? { label: option, value: option }
: option
)}
placeholder={`请选择${param.name}`}
className="w-full"
/>
</Form.Item>
);
case "radio":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Radio.Group
value={value}
onChange={(e) => updateValue(e.target.value)}
>
{(param.options || []).map((option: any) => (
<Radio
key={typeof option === "string" ? option : option.value}
value={typeof option === "string" ? option : option.value}
>
{typeof option === "string" ? option : option.label}
</Radio>
))}
</Radio.Group>
</Form.Item>
);
case "checkbox":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Checkbox.Group
value={value}
onChange={updateValue}
options={param.options || []}
/>
</Form.Item>
);
case "slider":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<div className="flex items-center gap-1">
<Slider
value={value}
onChange={updateValue}
tooltip={{ open: true }}
marks={{
[param.min || 0]: `${param.min || 0}`,
[param.min + (param.max - param.min) / 2]: `${
(param.min + param.max) / 2
}`,
[param.max || 100]: `${param.max || 100}`,
}}
min={param.min || 0}
max={param.max || 100}
step={param.step || 1}
className="flex-1"
/>
<InputNumber
min={param.min || 0}
max={param.max || 100}
step={param.step || 1}
value={value}
onChange={updateValue}
style={{ width: 80 }}
/>
</div>
</Form.Item>
);
case "range": {
const min = param.min || param?.properties?.[0]?.min || 0;
const max = param.max || param?.properties?.[0]?.max || 1;
const step = param.step || param?.properties?.[0]?.step || 0.1;
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Slider
value={Array.isArray(value) ? value : [value, value]}
onChange={(val) =>
updateValue(Array.isArray(val) ? val : [val, val])
}
range
min={min}
max={max }
step={step}
className="w-full"
/>
<Space>
<InputNumber
min={min}
max={max}
value={value[0]}
onChange={(val1) => updateValue([val1, value[1]])}
changeOnWheel
/>
~
<InputNumber
min={min}
max={max}
value={value[1]}
onChange={(val2) => updateValue([value[0], val2])}
changeOnWheel
/>
</Space>
</Form.Item>
);
}
case "inputNumber":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<InputNumber
value={value}
onChange={(val) => updateValue(val)}
placeholder={`请输入${param.name}`}
className="w-full"
min={param.min}
max={param.max}
step={param.step || 1}
/>
</Form.Item>
);
case "switch":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Checkbox
checked={value as boolean}
onChange={(e) => updateValue(e.target.checked)}
>
{param.name}
</Checkbox>
</Form.Item>
);
case "multiple":
return (
<div className="pl-4 border-l border-gray-300">
{param.properties.map((subParam) => (
<ParamConfig
key={subParam.key}
operator={operator}
paramKey={subParam.key}
param={subParam}
onParamChange={onParamChange}
/>
))}
</div>
);
default:
return null;
}
};
export default ParamConfig;
import React from "react";
import {
Input,
Select,
Radio,
Checkbox,
Form,
InputNumber,
Slider,
Space,
} from "antd";
import { ConfigI, OperatorI } from "@/pages/OperatorMarket/operator.model";
interface ParamConfigProps {
operator: OperatorI;
paramKey: string;
param: ConfigI;
onParamChange?: (operatorId: string, paramKey: string, value: any) => void;
}
const ParamConfig: React.FC<ParamConfigProps> = ({
operator,
paramKey,
param,
onParamChange,
}) => {
if (!param) return null;
let defaultVal: any = param.defaultVal;
if (param.type === "range") {
defaultVal = Array.isArray(param.defaultVal)
? param.defaultVal
: [
param?.properties?.[0]?.defaultVal,
param?.properties?.[1]?.defaultVal,
];
}
const [value, setValue] = React.useState(param.value || defaultVal);
const updateValue = (newValue: any) => {
setValue(newValue);
return onParamChange && onParamChange(operator.id, paramKey, newValue);
};
switch (param.type) {
case "input":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Input
value={value}
onChange={(e) => updateValue(e.target.value)}
placeholder={`请输入${param.name}`}
className="w-full"
/>
</Form.Item>
);
case "select":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Select
value={value}
onChange={updateValue}
options={(param.options || []).map((option: any) =>
typeof option === "string"
? { label: option, value: option }
: option
)}
placeholder={`请选择${param.name}`}
className="w-full"
/>
</Form.Item>
);
case "radio":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Radio.Group
value={value}
onChange={(e) => updateValue(e.target.value)}
>
{(param.options || []).map((option: any) => (
<Radio
key={typeof option === "string" ? option : option.value}
value={typeof option === "string" ? option : option.value}
>
{typeof option === "string" ? option : option.label}
</Radio>
))}
</Radio.Group>
</Form.Item>
);
case "checkbox":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Checkbox.Group
value={value}
onChange={updateValue}
options={param.options || []}
/>
</Form.Item>
);
case "slider":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<div className="flex items-center gap-1">
<Slider
value={value}
onChange={updateValue}
tooltip={{ open: true }}
marks={{
[param.min || 0]: `${param.min || 0}`,
[param.min + (param.max - param.min) / 2]: `${
(param.min + param.max) / 2
}`,
[param.max || 100]: `${param.max || 100}`,
}}
min={param.min || 0}
max={param.max || 100}
step={param.step || 1}
className="flex-1"
/>
<InputNumber
min={param.min || 0}
max={param.max || 100}
step={param.step || 1}
value={value}
onChange={updateValue}
style={{ width: 80 }}
/>
</div>
</Form.Item>
);
case "range": {
const min = param.min || param?.properties?.[0]?.min || 0;
const max = param.max || param?.properties?.[0]?.max || 1;
const step = param.step || param?.properties?.[0]?.step || 0.1;
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Slider
value={Array.isArray(value) ? value : [value, value]}
onChange={(val) =>
updateValue(Array.isArray(val) ? val : [val, val])
}
range
min={min}
max={max }
step={step}
className="w-full"
/>
<Space>
<InputNumber
min={min}
max={max}
value={value[0]}
onChange={(val1) => updateValue([val1, value[1]])}
changeOnWheel
/>
~
<InputNumber
min={min}
max={max}
value={value[1]}
onChange={(val2) => updateValue([value[0], val2])}
changeOnWheel
/>
</Space>
</Form.Item>
);
}
case "inputNumber":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<InputNumber
value={value}
onChange={(val) => updateValue(val)}
placeholder={`请输入${param.name}`}
className="w-full"
min={param.min}
max={param.max}
step={param.step || 1}
/>
</Form.Item>
);
case "switch":
return (
<Form.Item
label={param.name}
tooltip={param.description}
key={paramKey}
>
<Checkbox
checked={value as boolean}
onChange={(e) => updateValue(e.target.checked)}
>
{param.name}
</Checkbox>
</Form.Item>
);
case "multiple":
return (
<div className="pl-4 border-l border-gray-300">
{param.properties.map((subParam) => (
<ParamConfig
key={subParam.key}
operator={operator}
paramKey={subParam.key}
param={subParam}
onParamChange={onParamChange}
/>
))}
</div>
);
default:
return null;
}
};
export default ParamConfig;

View File

@@ -1,87 +1,87 @@
import { useDragOperators } from "./useDragOperators";
import { useOperatorOperations } from "./useOperatorOperations";
import OperatorConfig from "../components/OperatorConfig";
import OperatorLibrary from "../components/OperatorLibrary";
import OperatorOrchestration from "../components/OperatorOrchestration";
export function useCreateStepTwo() {
const {
operators,
selectedOperators,
templates,
currentTemplate,
configOperator,
currentStep,
categoryOptions,
handlePrev,
handleNext,
setCurrentTemplate,
setConfigOperator,
setSelectedOperators,
handleConfigChange,
toggleOperator,
removeOperator,
} = useOperatorOperations();
const {
handleDragStart,
handleDragEnd,
handleContainerDragOver,
handleContainerDragLeave,
handleItemDragOver,
handleItemDragLeave,
handleItemDrop,
handleDropToContainer,
} = useDragOperators({
operators: selectedOperators,
setOperators: setSelectedOperators,
});
const renderStepTwo = (
<div className="flex w-full h-full">
{/* 左侧算子库 */}
<OperatorLibrary
categoryOptions={categoryOptions}
selectedOperators={selectedOperators}
operatorList={operators}
setSelectedOperators={setSelectedOperators}
toggleOperator={toggleOperator}
handleDragStart={handleDragStart}
/>
{/* 中间算子编排区域 */}
<OperatorOrchestration
selectedOperators={selectedOperators}
configOperator={configOperator}
templates={templates}
currentTemplate={currentTemplate}
categoryOptions={categoryOptions}
setSelectedOperators={setSelectedOperators}
setConfigOperator={setConfigOperator}
setCurrentTemplate={setCurrentTemplate}
removeOperator={removeOperator}
handleDragStart={handleDragStart}
handleContainerDragLeave={handleContainerDragLeave}
handleContainerDragOver={handleContainerDragOver}
handleItemDragOver={handleItemDragOver}
handleItemDragLeave={handleItemDragLeave}
handleItemDrop={handleItemDrop}
handleDropToContainer={handleDropToContainer}
handleDragEnd={handleDragEnd}
/>
{/* 右侧参数配置面板 */}
<OperatorConfig
selectedOp={configOperator}
handleConfigChange={handleConfigChange}
/>
</div>
);
return {
renderStepTwo,
selectedOperators,
currentStep,
handlePrev,
handleNext,
};
}
import { useDragOperators } from "./useDragOperators";
import { useOperatorOperations } from "./useOperatorOperations";
import OperatorConfig from "../components/OperatorConfig";
import OperatorLibrary from "../components/OperatorLibrary";
import OperatorOrchestration from "../components/OperatorOrchestration";
export function useCreateStepTwo() {
const {
operators,
selectedOperators,
templates,
currentTemplate,
configOperator,
currentStep,
categoryOptions,
handlePrev,
handleNext,
setCurrentTemplate,
setConfigOperator,
setSelectedOperators,
handleConfigChange,
toggleOperator,
removeOperator,
} = useOperatorOperations();
const {
handleDragStart,
handleDragEnd,
handleContainerDragOver,
handleContainerDragLeave,
handleItemDragOver,
handleItemDragLeave,
handleItemDrop,
handleDropToContainer,
} = useDragOperators({
operators: selectedOperators,
setOperators: setSelectedOperators,
});
const renderStepTwo = (
<div className="flex w-full h-full">
{/* 左侧算子库 */}
<OperatorLibrary
categoryOptions={categoryOptions}
selectedOperators={selectedOperators}
operatorList={operators}
setSelectedOperators={setSelectedOperators}
toggleOperator={toggleOperator}
handleDragStart={handleDragStart}
/>
{/* 中间算子编排区域 */}
<OperatorOrchestration
selectedOperators={selectedOperators}
configOperator={configOperator}
templates={templates}
currentTemplate={currentTemplate}
categoryOptions={categoryOptions}
setSelectedOperators={setSelectedOperators}
setConfigOperator={setConfigOperator}
setCurrentTemplate={setCurrentTemplate}
removeOperator={removeOperator}
handleDragStart={handleDragStart}
handleContainerDragLeave={handleContainerDragLeave}
handleContainerDragOver={handleContainerDragOver}
handleItemDragOver={handleItemDragOver}
handleItemDragLeave={handleItemDragLeave}
handleItemDrop={handleItemDrop}
handleDropToContainer={handleDropToContainer}
handleDragEnd={handleDragEnd}
/>
{/* 右侧参数配置面板 */}
<OperatorConfig
selectedOp={configOperator}
handleConfigChange={handleConfigChange}
/>
</div>
);
return {
renderStepTwo,
selectedOperators,
currentStep,
handlePrev,
handleNext,
};
}

View File

@@ -1,158 +1,158 @@
import { OperatorI } from "@/pages/OperatorMarket/operator.model";
import React, { useState } from "react";
export function useDragOperators({
operators,
setOperators,
}: {
operators: OperatorI[];
setOperators: (operators: OperatorI[]) => void;
}) {
const [draggingItem, setDraggingItem] = useState<OperatorI | null>(null);
const [draggingSource, setDraggingSource] = useState<
"library" | "sort" | null
>(null);
const [insertPosition, setInsertPosition] = useState<
"above" | "below" | null
>(null);
// 处理拖拽开始
const handleDragStart = (
e: React.DragEvent,
item: OperatorI,
source: "library" | "sort"
) => {
setDraggingItem({
...item,
originalId: item.id,
});
setDraggingSource(source);
e.dataTransfer.effectAllowed = "move";
};
// 处理拖拽结束
const handleDragEnd = () => {
setDraggingItem(null);
setInsertPosition(null);
};
// 处理容器拖拽经过
const handleContainerDragOver = (e: React.DragEvent) => {
e.preventDefault();
};
// 处理容器拖拽离开
const handleContainerDragLeave = (e: React.DragEvent) => {
if (!e.currentTarget.contains(e.relatedTarget)) {
setInsertPosition(null);
}
};
// 处理项目拖拽经过
const handleItemDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
const rect = e.currentTarget.getBoundingClientRect();
const mouseY = e.clientY;
const elementMiddle = rect.top + rect.height / 2;
// 判断鼠标在元素的上半部分还是下半部分
const newPosition = mouseY < elementMiddle ? "above" : "below";
setInsertPosition(newPosition);
};
// 处理项目拖拽离开
const handleItemDragLeave = (e: React.DragEvent) => {
if (!e.currentTarget.contains(e.relatedTarget)) {
setInsertPosition(null);
}
};
// 处理放置到空白区域
const handleDropToContainer = (e: React.DragEvent) => {
e.preventDefault();
if (!draggingItem) return;
// 如果是从算子库拖拽过来的
if (draggingSource === "library") {
// 检查是否已存在
const exists = operators.some((item) => item.id === draggingItem.id);
if (!exists) {
setOperators([...operators, draggingItem]);
}
}
resetDragState();
};
// 处理放置到特定位置
const handleItemDrop = (e: React.DragEvent, targetIndex: number) => {
e.preventDefault();
e.stopPropagation();
if (!draggingItem) return;
// 从左侧拖拽到右侧的精确插入
if (draggingSource === "library") {
if (targetIndex !== -1) {
const insertIndex =
insertPosition === "above" ? targetIndex : targetIndex + 1;
// 检查是否已存在
const exists = operators.some((item) => item.id === draggingItem.id);
if (!exists) {
const newRightItems = [...operators];
newRightItems.splice(insertIndex, 0, draggingItem);
setOperators(newRightItems);
}
}
}
// 右侧容器内的重新排序
else if (draggingSource === "sort") {
const draggedIndex = operators.findIndex(
(item) => item.id === draggingItem.id
);
if (
draggedIndex !== -1 &&
targetIndex !== -1 &&
draggedIndex !== targetIndex
) {
const newItems = [...operators];
const [draggedItem] = newItems.splice(draggedIndex, 1);
// 计算正确的插入位置
let insertIndex =
insertPosition === "above" ? targetIndex : targetIndex + 1;
if (draggedIndex < insertIndex) {
insertIndex--; // 调整插入位置,因为已经移除了原元素
}
newItems.splice(insertIndex, 0, draggedItem);
setOperators(newItems);
}
}
resetDragState();
};
// 重置拖拽状态
const resetDragState = () => {
setDraggingItem(null);
setInsertPosition(null);
};
return {
handleDragStart,
handleDragEnd,
handleContainerDragOver,
handleContainerDragLeave,
handleItemDragOver,
handleItemDragLeave,
handleItemDrop,
handleDropToContainer,
};
}
import { OperatorI } from "@/pages/OperatorMarket/operator.model";
import React, { useState } from "react";
export function useDragOperators({
operators,
setOperators,
}: {
operators: OperatorI[];
setOperators: (operators: OperatorI[]) => void;
}) {
const [draggingItem, setDraggingItem] = useState<OperatorI | null>(null);
const [draggingSource, setDraggingSource] = useState<
"library" | "sort" | null
>(null);
const [insertPosition, setInsertPosition] = useState<
"above" | "below" | null
>(null);
// 处理拖拽开始
const handleDragStart = (
e: React.DragEvent,
item: OperatorI,
source: "library" | "sort"
) => {
setDraggingItem({
...item,
originalId: item.id,
});
setDraggingSource(source);
e.dataTransfer.effectAllowed = "move";
};
// 处理拖拽结束
const handleDragEnd = () => {
setDraggingItem(null);
setInsertPosition(null);
};
// 处理容器拖拽经过
const handleContainerDragOver = (e: React.DragEvent) => {
e.preventDefault();
};
// 处理容器拖拽离开
const handleContainerDragLeave = (e: React.DragEvent) => {
if (!e.currentTarget.contains(e.relatedTarget)) {
setInsertPosition(null);
}
};
// 处理项目拖拽经过
const handleItemDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
const rect = e.currentTarget.getBoundingClientRect();
const mouseY = e.clientY;
const elementMiddle = rect.top + rect.height / 2;
// 判断鼠标在元素的上半部分还是下半部分
const newPosition = mouseY < elementMiddle ? "above" : "below";
setInsertPosition(newPosition);
};
// 处理项目拖拽离开
const handleItemDragLeave = (e: React.DragEvent) => {
if (!e.currentTarget.contains(e.relatedTarget)) {
setInsertPosition(null);
}
};
// 处理放置到空白区域
const handleDropToContainer = (e: React.DragEvent) => {
e.preventDefault();
if (!draggingItem) return;
// 如果是从算子库拖拽过来的
if (draggingSource === "library") {
// 检查是否已存在
const exists = operators.some((item) => item.id === draggingItem.id);
if (!exists) {
setOperators([...operators, draggingItem]);
}
}
resetDragState();
};
// 处理放置到特定位置
const handleItemDrop = (e: React.DragEvent, targetIndex: number) => {
e.preventDefault();
e.stopPropagation();
if (!draggingItem) return;
// 从左侧拖拽到右侧的精确插入
if (draggingSource === "library") {
if (targetIndex !== -1) {
const insertIndex =
insertPosition === "above" ? targetIndex : targetIndex + 1;
// 检查是否已存在
const exists = operators.some((item) => item.id === draggingItem.id);
if (!exists) {
const newRightItems = [...operators];
newRightItems.splice(insertIndex, 0, draggingItem);
setOperators(newRightItems);
}
}
}
// 右侧容器内的重新排序
else if (draggingSource === "sort") {
const draggedIndex = operators.findIndex(
(item) => item.id === draggingItem.id
);
if (
draggedIndex !== -1 &&
targetIndex !== -1 &&
draggedIndex !== targetIndex
) {
const newItems = [...operators];
const [draggedItem] = newItems.splice(draggedIndex, 1);
// 计算正确的插入位置
let insertIndex =
insertPosition === "above" ? targetIndex : targetIndex + 1;
if (draggedIndex < insertIndex) {
insertIndex--; // 调整插入位置,因为已经移除了原元素
}
newItems.splice(insertIndex, 0, draggedItem);
setOperators(newItems);
}
}
resetDragState();
};
// 重置拖拽状态
const resetDragState = () => {
setDraggingItem(null);
setInsertPosition(null);
};
return {
handleDragStart,
handleDragEnd,
handleContainerDragOver,
handleContainerDragLeave,
handleItemDragOver,
handleItemDragLeave,
handleItemDrop,
handleDropToContainer,
};
}

View File

@@ -1,169 +1,169 @@
import { useEffect, useState } from "react";
import { OperatorI } from "@/pages/OperatorMarket/operator.model";
import { CleansingTemplate } from "../../cleansing.model";
import {queryCleaningTemplateByIdUsingGet, queryCleaningTemplatesUsingGet} from "../../cleansing.api";
import {
queryCategoryTreeUsingGet,
queryOperatorsUsingPost,
} from "@/pages/OperatorMarket/operator.api";
import {useParams} from "react-router";
export function useOperatorOperations() {
const { id = "" } = useParams();
const [currentStep, setCurrentStep] = useState(1);
const [operators, setOperators] = useState<OperatorI[]>([]);
const [selectedOperators, setSelectedOperators] = useState<OperatorI[]>([]);
const [configOperator, setConfigOperator] = useState<OperatorI | null>(null);
const [templates, setTemplates] = useState<CleansingTemplate[]>([]);
const [currentTemplate, setCurrentTemplate] =
useState<CleansingTemplate | null>(null);
// 将后端返回的算子数据映射为前端需要的格式
const mapOperator = (op: OperatorI) => {
const configs =
op.settings
? JSON.parse(op.settings)
: {};
const defaultParams: Record<string, string> = {};
Object.keys(configs).forEach((key) => {
const { value } = configs[key];
defaultParams[key] = value;
});
return {
...op,
defaultParams,
configs,
};
};
const [categoryOptions, setCategoryOptions] = useState([]);
const initOperators = async () => {
const [categoryRes, operatorRes] = await Promise.all([
queryCategoryTreeUsingGet(),
queryOperatorsUsingPost({ page: 0, size: 1000 }),
]);
const operators = operatorRes.data.content.map(mapOperator);
setOperators(operators || []);
const options = categoryRes.data.content.reduce((acc: any[], item: any) => {
const cats = item.categories.map((cat) => ({
...cat,
type: item.name,
label: cat.name,
value: cat.id,
icon: cat.icon,
operators: operators.filter((op) => op[item.name] === cat.name),
}));
acc.push(...cats);
return acc;
}, [] as { id: string; name: string; icon: React.ReactNode }[]);
setCategoryOptions(options);
};
const initTemplates = async () => {
if (id) {
const { data } = await queryCleaningTemplateByIdUsingGet(id);
const template = {
...data,
label: data.name,
value: data.id,
}
setTemplates([template])
setCurrentTemplate(template)
} else {
const { data } = await queryCleaningTemplatesUsingGet();
const newTemplates =
data.content?.map?.((item) => ({
...item,
label: item.name,
value: item.id,
})) || [];
setTemplates(newTemplates);
setCurrentTemplate(newTemplates?.[0])
}
};
useEffect(() => {
setSelectedOperators(currentTemplate?.instance?.map(mapOperator) || []);
}, [currentTemplate]);
useEffect(() => {
initTemplates();
initOperators();
}, []);
const toggleOperator = (operator: OperatorI) => {
const exist = selectedOperators.find((op) => op.id === operator.id);
if (exist) {
setSelectedOperators(
selectedOperators.filter((op) => op.id !== operator.id)
);
} else {
setSelectedOperators([...selectedOperators, { ...operator }]);
}
};
// 删除算子
const removeOperator = (id: string) => {
setSelectedOperators(selectedOperators.filter((op) => op.id !== id));
if (configOperator?.id === id) setConfigOperator(null);
};
// 配置算子参数变化
const handleConfigChange = (
operatorId: string,
paramKey: string,
value: any
) => {
setSelectedOperators((prev) =>
prev.map((op) =>
op.id === operatorId
? {
...op,
overrides: {
...(op?.overrides || op?.defaultParams),
[paramKey]: value,
},
}
: op
)
);
};
const handleNext = () => {
if (currentStep < 2) {
setCurrentStep(currentStep + 1);
}
};
const handlePrev = () => {
if (currentStep > 1) {
setCurrentStep(currentStep - 1);
}
};
return {
currentStep,
templates,
currentTemplate,
configOperator,
categoryOptions,
setConfigOperator,
setCurrentTemplate,
setCurrentStep,
operators,
setOperators,
selectedOperators,
setSelectedOperators,
handleConfigChange,
toggleOperator,
removeOperator,
handleNext,
handlePrev,
};
}
import { useEffect, useState } from "react";
import { OperatorI } from "@/pages/OperatorMarket/operator.model";
import { CleansingTemplate } from "../../cleansing.model";
import {queryCleaningTemplateByIdUsingGet, queryCleaningTemplatesUsingGet} from "../../cleansing.api";
import {
queryCategoryTreeUsingGet,
queryOperatorsUsingPost,
} from "@/pages/OperatorMarket/operator.api";
import {useParams} from "react-router";
export function useOperatorOperations() {
const { id = "" } = useParams();
const [currentStep, setCurrentStep] = useState(1);
const [operators, setOperators] = useState<OperatorI[]>([]);
const [selectedOperators, setSelectedOperators] = useState<OperatorI[]>([]);
const [configOperator, setConfigOperator] = useState<OperatorI | null>(null);
const [templates, setTemplates] = useState<CleansingTemplate[]>([]);
const [currentTemplate, setCurrentTemplate] =
useState<CleansingTemplate | null>(null);
// 将后端返回的算子数据映射为前端需要的格式
const mapOperator = (op: OperatorI) => {
const configs =
op.settings
? JSON.parse(op.settings)
: {};
const defaultParams: Record<string, string> = {};
Object.keys(configs).forEach((key) => {
const { value } = configs[key];
defaultParams[key] = value;
});
return {
...op,
defaultParams,
configs,
};
};
const [categoryOptions, setCategoryOptions] = useState([]);
const initOperators = async () => {
const [categoryRes, operatorRes] = await Promise.all([
queryCategoryTreeUsingGet(),
queryOperatorsUsingPost({ page: 0, size: 1000 }),
]);
const operators = operatorRes.data.content.map(mapOperator);
setOperators(operators || []);
const options = categoryRes.data.content.reduce((acc: any[], item: any) => {
const cats = item.categories.map((cat) => ({
...cat,
type: item.name,
label: cat.name,
value: cat.id,
icon: cat.icon,
operators: operators.filter((op) => op[item.name] === cat.name),
}));
acc.push(...cats);
return acc;
}, [] as { id: string; name: string; icon: React.ReactNode }[]);
setCategoryOptions(options);
};
const initTemplates = async () => {
if (id) {
const { data } = await queryCleaningTemplateByIdUsingGet(id);
const template = {
...data,
label: data.name,
value: data.id,
}
setTemplates([template])
setCurrentTemplate(template)
} else {
const { data } = await queryCleaningTemplatesUsingGet();
const newTemplates =
data.content?.map?.((item) => ({
...item,
label: item.name,
value: item.id,
})) || [];
setTemplates(newTemplates);
setCurrentTemplate(newTemplates?.[0])
}
};
useEffect(() => {
setSelectedOperators(currentTemplate?.instance?.map(mapOperator) || []);
}, [currentTemplate]);
useEffect(() => {
initTemplates();
initOperators();
}, []);
const toggleOperator = (operator: OperatorI) => {
const exist = selectedOperators.find((op) => op.id === operator.id);
if (exist) {
setSelectedOperators(
selectedOperators.filter((op) => op.id !== operator.id)
);
} else {
setSelectedOperators([...selectedOperators, { ...operator }]);
}
};
// 删除算子
const removeOperator = (id: string) => {
setSelectedOperators(selectedOperators.filter((op) => op.id !== id));
if (configOperator?.id === id) setConfigOperator(null);
};
// 配置算子参数变化
const handleConfigChange = (
operatorId: string,
paramKey: string,
value: any
) => {
setSelectedOperators((prev) =>
prev.map((op) =>
op.id === operatorId
? {
...op,
overrides: {
...(op?.overrides || op?.defaultParams),
[paramKey]: value,
},
}
: op
)
);
};
const handleNext = () => {
if (currentStep < 2) {
setCurrentStep(currentStep + 1);
}
};
const handlePrev = () => {
if (currentStep > 1) {
setCurrentStep(currentStep - 1);
}
};
return {
currentStep,
templates,
currentTemplate,
configOperator,
categoryOptions,
setConfigOperator,
setCurrentTemplate,
setCurrentStep,
operators,
setOperators,
selectedOperators,
setSelectedOperators,
handleConfigChange,
toggleOperator,
removeOperator,
handleNext,
handlePrev,
};
}

View File

@@ -1,223 +1,223 @@
import { useEffect, useState } from "react";
import {Breadcrumb, App, Tabs} from "antd";
import {
Play,
Pause,
Clock,
CheckCircle,
AlertCircle,
Trash2,
Activity, LayoutList,
} from "lucide-react";
import DetailHeader from "@/components/DetailHeader";
import { Link, useNavigate, useParams } from "react-router";
import {
deleteCleaningTaskByIdUsingDelete,
executeCleaningTaskUsingPost,
queryCleaningTaskByIdUsingGet, queryCleaningTaskLogByIdUsingGet, queryCleaningTaskResultByIdUsingGet,
stopCleaningTaskUsingPost,
} from "../cleansing.api";
import {mapTask, TaskStatusMap} from "../cleansing.const";
import {CleansingResult, TaskStatus} from "@/pages/DataCleansing/cleansing.model";
import BasicInfo from "./components/BasicInfo";
import OperatorTable from "./components/OperatorTable";
import FileTable from "./components/FileTable";
import LogsTable from "./components/LogsTable";
import {formatExecutionDuration} from "@/utils/unit.ts";
import {ReloadOutlined} from "@ant-design/icons";
// 任务详情页面组件
export default function CleansingTaskDetail() {
const { id = "" } = useParams(); // 获取动态路由参数
const { message } = App.useApp();
const navigate = useNavigate();
const fetchTaskDetail = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTaskByIdUsingGet(id);
setTask(mapTask(data));
} catch (error) {
message.error("获取任务详情失败");
navigate("/data/cleansing");
}
};
const pauseTask = async () => {
await stopCleaningTaskUsingPost(id);
message.success("任务已暂停");
fetchTaskDetail();
};
const startTask = async () => {
await executeCleaningTaskUsingPost(id);
message.success("任务已启动");
fetchTaskDetail();
};
const deleteTask = async () => {
await deleteCleaningTaskByIdUsingDelete(id);
message.success("任务已删除");
navigate("/data/cleansing");
};
const [result, setResult] = useState<CleansingResult[]>();
const fetchTaskResult = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTaskResultByIdUsingGet(id);
setResult(data);
} catch (error) {
message.error("获取清洗结果失败");
navigate("/data/cleansing/task-detail/" + id);
}
};
const [taskLog, setTaskLog] = useState();
const fetchTaskLog = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTaskLogByIdUsingGet(id);
setTaskLog(data);
} catch (error) {
message.error("获取清洗日志失败");
navigate("/data/cleansing/task-detail/" + id);
}
};
const handleRefresh = async () => {
fetchTaskDetail();
{activeTab === "files" && await fetchTaskResult()}
{activeTab === "logs" && await fetchTaskLog()}
};
useEffect(() => {
fetchTaskDetail();
}, [id]);
const [task, setTask] = useState(null);
const [activeTab, setActiveTab] = useState("basic");
const headerData = {
...task,
icon: <LayoutList className="w-8 h-8" />,
status: TaskStatusMap[task?.status],
createdAt: task?.createdAt,
lastUpdated: task?.updatedAt,
};
const statistics = [
{
icon: <Clock className="w-4 h-4 text-blue-500" />,
label: "总耗时",
value: formatExecutionDuration(task?.startedAt, task?.finishedAt) || "--",
},
{
icon: <CheckCircle className="w-4 h-4 text-green-500" />,
label: "成功文件",
value: task?.progress?.succeedFileNum || "0",
},
{
icon: <AlertCircle className="w-4 h-4 text-red-500" />,
label: "失败文件",
value: (task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress.failedFileNum :
task?.progress?.totalFileNum - task?.progress.succeedFileNum,
},
{
icon: <Activity className="w-4 h-4 text-purple-500" />,
label: "成功率",
value: task?.progress?.successRate ? task?.progress?.successRate + "%" : "--",
},
];
const operations = [
...(task?.status === TaskStatus.RUNNING
? [
{
key: "pause",
label: "暂停任务",
icon: <Pause className="w-4 h-4" />,
onClick: pauseTask,
},
]
: []),
...([TaskStatus.PENDING, TaskStatus.STOPPED, TaskStatus.FAILED].includes(task?.status?.value)
? [
{
key: "start",
label: "执行任务",
icon: <Play className="w-4 h-4" />,
onClick: startTask,
},
]
: []),
{
key: "refresh",
label: "更新任务",
icon: <ReloadOutlined className="w-4 h-4" />,
onClick: handleRefresh,
},
{
key: "delete",
label: "删除任务",
icon: <Trash2 className="w-4 h-4" />,
danger: true,
onClick: deleteTask,
},
];
const tabList = [
{
key: "basic",
label: "基本信息",
},
{
key: "operators",
label: "处理算子",
},
{
key: "files",
label: "处理文件",
},
{
key: "logs",
label: "运行日志",
},
];
const breadItems = [
{
title: <Link to="/data/cleansing"></Link>,
},
{
title: "清洗任务详情",
},
];
return (
<>
<Breadcrumb items={breadItems} />
<div className="mb-4 mt-4">
<DetailHeader
data={headerData}
statistics={statistics}
operations={operations}
/>
</div>
<div className="flex-overflow-auto p-6 pt-2 bg-white rounded-md shadow">
<Tabs activeKey={activeTab} items={tabList} onChange={setActiveTab} />
<div className="h-full flex-1 overflow-auto">
{activeTab === "basic" && (
<BasicInfo task={task} />
)}
{activeTab === "operators" && <OperatorTable task={task} />}
{activeTab === "files" && <FileTable result={result} fetchTaskResult={fetchTaskResult} />}
{activeTab === "logs" && <LogsTable taskLog={taskLog} fetchTaskLog={fetchTaskLog} />}
</div>
</div>
</>
);
}
import { useEffect, useState } from "react";
import {Breadcrumb, App, Tabs} from "antd";
import {
Play,
Pause,
Clock,
CheckCircle,
AlertCircle,
Trash2,
Activity, LayoutList,
} from "lucide-react";
import DetailHeader from "@/components/DetailHeader";
import { Link, useNavigate, useParams } from "react-router";
import {
deleteCleaningTaskByIdUsingDelete,
executeCleaningTaskUsingPost,
queryCleaningTaskByIdUsingGet, queryCleaningTaskLogByIdUsingGet, queryCleaningTaskResultByIdUsingGet,
stopCleaningTaskUsingPost,
} from "../cleansing.api";
import {mapTask, TaskStatusMap} from "../cleansing.const";
import {CleansingResult, TaskStatus} from "@/pages/DataCleansing/cleansing.model";
import BasicInfo from "./components/BasicInfo";
import OperatorTable from "./components/OperatorTable";
import FileTable from "./components/FileTable";
import LogsTable from "./components/LogsTable";
import {formatExecutionDuration} from "@/utils/unit.ts";
import {ReloadOutlined} from "@ant-design/icons";
// 任务详情页面组件
export default function CleansingTaskDetail() {
const { id = "" } = useParams(); // 获取动态路由参数
const { message } = App.useApp();
const navigate = useNavigate();
const fetchTaskDetail = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTaskByIdUsingGet(id);
setTask(mapTask(data));
} catch (error) {
message.error("获取任务详情失败");
navigate("/data/cleansing");
}
};
const pauseTask = async () => {
await stopCleaningTaskUsingPost(id);
message.success("任务已暂停");
fetchTaskDetail();
};
const startTask = async () => {
await executeCleaningTaskUsingPost(id);
message.success("任务已启动");
fetchTaskDetail();
};
const deleteTask = async () => {
await deleteCleaningTaskByIdUsingDelete(id);
message.success("任务已删除");
navigate("/data/cleansing");
};
const [result, setResult] = useState<CleansingResult[]>();
const fetchTaskResult = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTaskResultByIdUsingGet(id);
setResult(data);
} catch (error) {
message.error("获取清洗结果失败");
navigate("/data/cleansing/task-detail/" + id);
}
};
const [taskLog, setTaskLog] = useState();
const fetchTaskLog = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTaskLogByIdUsingGet(id);
setTaskLog(data);
} catch (error) {
message.error("获取清洗日志失败");
navigate("/data/cleansing/task-detail/" + id);
}
};
const handleRefresh = async () => {
fetchTaskDetail();
{activeTab === "files" && await fetchTaskResult()}
{activeTab === "logs" && await fetchTaskLog()}
};
useEffect(() => {
fetchTaskDetail();
}, [id]);
const [task, setTask] = useState(null);
const [activeTab, setActiveTab] = useState("basic");
const headerData = {
...task,
icon: <LayoutList className="w-8 h-8" />,
status: TaskStatusMap[task?.status],
createdAt: task?.createdAt,
lastUpdated: task?.updatedAt,
};
const statistics = [
{
icon: <Clock className="w-4 h-4 text-blue-500" />,
label: "总耗时",
value: formatExecutionDuration(task?.startedAt, task?.finishedAt) || "--",
},
{
icon: <CheckCircle className="w-4 h-4 text-green-500" />,
label: "成功文件",
value: task?.progress?.succeedFileNum || "0",
},
{
icon: <AlertCircle className="w-4 h-4 text-red-500" />,
label: "失败文件",
value: (task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress.failedFileNum :
task?.progress?.totalFileNum - task?.progress.succeedFileNum,
},
{
icon: <Activity className="w-4 h-4 text-purple-500" />,
label: "成功率",
value: task?.progress?.successRate ? task?.progress?.successRate + "%" : "--",
},
];
const operations = [
...(task?.status === TaskStatus.RUNNING
? [
{
key: "pause",
label: "暂停任务",
icon: <Pause className="w-4 h-4" />,
onClick: pauseTask,
},
]
: []),
...([TaskStatus.PENDING, TaskStatus.STOPPED, TaskStatus.FAILED].includes(task?.status?.value)
? [
{
key: "start",
label: "执行任务",
icon: <Play className="w-4 h-4" />,
onClick: startTask,
},
]
: []),
{
key: "refresh",
label: "更新任务",
icon: <ReloadOutlined className="w-4 h-4" />,
onClick: handleRefresh,
},
{
key: "delete",
label: "删除任务",
icon: <Trash2 className="w-4 h-4" />,
danger: true,
onClick: deleteTask,
},
];
const tabList = [
{
key: "basic",
label: "基本信息",
},
{
key: "operators",
label: "处理算子",
},
{
key: "files",
label: "处理文件",
},
{
key: "logs",
label: "运行日志",
},
];
const breadItems = [
{
title: <Link to="/data/cleansing"></Link>,
},
{
title: "清洗任务详情",
},
];
return (
<>
<Breadcrumb items={breadItems} />
<div className="mb-4 mt-4">
<DetailHeader
data={headerData}
statistics={statistics}
operations={operations}
/>
</div>
<div className="flex-overflow-auto p-6 pt-2 bg-white rounded-md shadow">
<Tabs activeKey={activeTab} items={tabList} onChange={setActiveTab} />
<div className="h-full flex-1 overflow-auto">
{activeTab === "basic" && (
<BasicInfo task={task} />
)}
{activeTab === "operators" && <OperatorTable task={task} />}
{activeTab === "files" && <FileTable result={result} fetchTaskResult={fetchTaskResult} />}
{activeTab === "logs" && <LogsTable taskLog={taskLog} fetchTaskLog={fetchTaskLog} />}
</div>
</div>
</>
);
}

View File

@@ -1,122 +1,122 @@
import { useEffect, useState } from "react";
import {Breadcrumb, App, Tabs} from "antd";
import {
Trash2,
LayoutList,
} from "lucide-react";
import DetailHeader from "@/components/DetailHeader";
import { Link, useNavigate, useParams } from "react-router";
import {
deleteCleaningTemplateByIdUsingDelete,
queryCleaningTemplateByIdUsingGet,
} from "../cleansing.api";
import {mapTemplate} from "../cleansing.const";
import OperatorTable from "./components/OperatorTable";
import {EditOutlined, ReloadOutlined, NumberOutlined} from "@ant-design/icons";
// 任务详情页面组件
export default function CleansingTemplateDetail() {
const { id = "" } = useParams(); // 获取动态路由参数
const { message } = App.useApp();
const navigate = useNavigate();
const [template, setTemplate] = useState();
const fetchTemplateDetail = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTemplateByIdUsingGet(id);
setTemplate(mapTemplate(data));
} catch (error) {
message.error("获取任务详情失败");
navigate("/data/cleansing");
}
};
const deleteTemplate = async () => {
await deleteCleaningTemplateByIdUsingDelete(id);
message.success("模板已删除");
navigate("/data/cleansing");
};
const handleRefresh = async () => {
fetchTemplateDetail();
};
useEffect(() => {
fetchTemplateDetail();
}, [id]);
const [activeTab, setActiveTab] = useState("operators");
const headerData = {
...template,
icon: <LayoutList className="w-8 h-8" />,
createdAt: template?.createdAt,
lastUpdated: template?.updatedAt,
};
const statistics = [
{
icon: <NumberOutlined className="w-4 h-4 text-green-500" />,
label: "算子数量",
value: template?.instance?.length || 0,
},
];
const operations = [
{
key: "update",
label: "更新任务",
icon: <EditOutlined className="w-4 h-4" />,
onClick: () => navigate(`/data/cleansing/update-template/${id}`),
},
{
key: "refresh",
label: "更新任务",
icon: <ReloadOutlined className="w-4 h-4" />,
onClick: handleRefresh,
},
{
key: "delete",
label: "删除任务",
icon: <Trash2 className="w-4 h-4" />,
danger: true,
onClick: deleteTemplate,
},
];
const tabList = [
{
key: "operators",
label: "处理算子",
},
];
const breadItems = [
{
title: <Link to="/data/cleansing"></Link>,
},
{
title: "模板详情",
},
];
return (
<>
<Breadcrumb items={breadItems} />
<div className="mb-4 mt-4">
<DetailHeader
data={headerData}
statistics={statistics}
operations={operations}
/>
</div>
<div className="flex-overflow-auto p-6 pt-2 bg-white rounded-md shadow">
<Tabs activeKey={activeTab} items={tabList} onChange={setActiveTab} />
<div className="h-full flex-1 overflow-auto">
<OperatorTable task={template} />
</div>
</div>
</>
);
}
import { useEffect, useState } from "react";
import {Breadcrumb, App, Tabs} from "antd";
import {
Trash2,
LayoutList,
} from "lucide-react";
import DetailHeader from "@/components/DetailHeader";
import { Link, useNavigate, useParams } from "react-router";
import {
deleteCleaningTemplateByIdUsingDelete,
queryCleaningTemplateByIdUsingGet,
} from "../cleansing.api";
import {mapTemplate} from "../cleansing.const";
import OperatorTable from "./components/OperatorTable";
import {EditOutlined, ReloadOutlined, NumberOutlined} from "@ant-design/icons";
// 任务详情页面组件
export default function CleansingTemplateDetail() {
const { id = "" } = useParams(); // 获取动态路由参数
const { message } = App.useApp();
const navigate = useNavigate();
const [template, setTemplate] = useState();
const fetchTemplateDetail = async () => {
if (!id) return;
try {
const { data } = await queryCleaningTemplateByIdUsingGet(id);
setTemplate(mapTemplate(data));
} catch (error) {
message.error("获取任务详情失败");
navigate("/data/cleansing");
}
};
const deleteTemplate = async () => {
await deleteCleaningTemplateByIdUsingDelete(id);
message.success("模板已删除");
navigate("/data/cleansing");
};
const handleRefresh = async () => {
fetchTemplateDetail();
};
useEffect(() => {
fetchTemplateDetail();
}, [id]);
const [activeTab, setActiveTab] = useState("operators");
const headerData = {
...template,
icon: <LayoutList className="w-8 h-8" />,
createdAt: template?.createdAt,
lastUpdated: template?.updatedAt,
};
const statistics = [
{
icon: <NumberOutlined className="w-4 h-4 text-green-500" />,
label: "算子数量",
value: template?.instance?.length || 0,
},
];
const operations = [
{
key: "update",
label: "更新任务",
icon: <EditOutlined className="w-4 h-4" />,
onClick: () => navigate(`/data/cleansing/update-template/${id}`),
},
{
key: "refresh",
label: "更新任务",
icon: <ReloadOutlined className="w-4 h-4" />,
onClick: handleRefresh,
},
{
key: "delete",
label: "删除任务",
icon: <Trash2 className="w-4 h-4" />,
danger: true,
onClick: deleteTemplate,
},
];
const tabList = [
{
key: "operators",
label: "处理算子",
},
];
const breadItems = [
{
title: <Link to="/data/cleansing"></Link>,
},
{
title: "模板详情",
},
];
return (
<>
<Breadcrumb items={breadItems} />
<div className="mb-4 mt-4">
<DetailHeader
data={headerData}
statistics={statistics}
operations={operations}
/>
</div>
<div className="flex-overflow-auto p-6 pt-2 bg-white rounded-md shadow">
<Tabs activeKey={activeTab} items={tabList} onChange={setActiveTab} />
<div className="h-full flex-1 overflow-auto">
<OperatorTable task={template} />
</div>
</div>
</>
);
}

View File

@@ -1,138 +1,138 @@
import {CleansingTask, TaskStatus} from "@/pages/DataCleansing/cleansing.model";
import { Button, Card, Descriptions, Progress } from "antd";
import { Activity, AlertCircle, CheckCircle, Clock } from "lucide-react";
import { useNavigate } from "react-router";
import {formatExecutionDuration} from "@/utils/unit.ts";
export default function BasicInfo({ task }: { task: CleansingTask }) {
const navigate = useNavigate();
const descriptionItems = [
{
key: "id",
label: "任务ID",
children: <span className="font-mono">{task?.id}</span>,
},
{ key: "name", label: "任务名称", children: task?.name },
{
key: "dataset",
label: "源数据集",
children: (
<Button
style={{ paddingLeft: 0, marginLeft: 0 }}
type="link"
size="small"
onClick={() =>
navigate("/data/management/detail/" + task?.srcDatasetId)
}
>
{task?.srcDatasetName}
</Button>
),
},
{
key: "targetDataset",
label: "目标数据集",
children: (
<Button
style={{ paddingLeft: 0, marginLeft: 0 }}
type="link"
size="small"
onClick={() =>
navigate("/data/management/detail/" + task?.destDatasetId)
}
>
{task?.destDatasetName}
</Button>
),
},
{ key: "startTime", label: "开始时间", children: task?.startedAt },
{
key: "description",
label: "任务描述",
children: (
<span className="text-gray-600">{task?.description || "--"}</span>
),
span: 2,
},
];
return (
<>
{/* 执行摘要 */}
<Card className="mb-6">
<div className="grid grid-cols-4 gap-4">
<div className="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg">
<Clock className="w-8 h-8 text-blue-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-blue-500">
{formatExecutionDuration(task?.startedAt, task?.finishedAt) || "--"}
</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-lg">
<CheckCircle className="w-8 h-8 text-green-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-green-500">
{task?.progress?.succeedFileNum || "0"}
</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-lg">
<AlertCircle className="w-8 h-8 text-red-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-red-500">
{(task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress.failedFileNum :
task?.progress?.totalFileNum - task?.progress.succeedFileNum}
</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg">
<Activity className="w-8 h-8 text-purple-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-purple-500">
{task?.progress?.successRate ? task?.progress?.successRate + "%" : "--"}
</div>
<div className="text-sm text-gray-600"></div>
</div>
</div>
</Card>
{/* 基本信息 */}
<Card>
<div className="mb-8">
<h3 className="text-lg font-semibold text-gray-900 mb-4"></h3>
<Descriptions
column={2}
bordered={false}
size="middle"
labelStyle={{ fontWeight: 500, color: "#555" }}
contentStyle={{ fontSize: 14 }}
items={descriptionItems}
></Descriptions>
</div>
{/* 处理进度 */}
<div>
<h3 className="text-lg font-semibold text-gray-900 mb-4"></h3>
{ task?.status?.value === TaskStatus.FAILED ?
<Progress percent={task?.progress?.process} size="small" status="exception" />
: <Progress percent={task?.progress?.process} size="small"/>
}
<div className="grid grid-cols-2 gap-4 text-sm mt-4">
<div className="flex items-center gap-2">
<span className="w-3 h-3 bg-green-500 rounded-full inline-block" />
<span>: {task?.progress?.succeedFileNum || "0"}</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 bg-blue-500 rounded-full inline-block" />
<span>: {(task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress?.totalFileNum - task?.progress.succeedFileNum : 0}</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 bg-red-500 rounded-full inline-block" />
<span>: {(task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress.failedFileNum :
task?.progress?.totalFileNum - task?.progress.succeedFileNum}</span>
</div>
</div>
</div>
</Card>
</>
);
}
import {CleansingTask, TaskStatus} from "@/pages/DataCleansing/cleansing.model";
import { Button, Card, Descriptions, Progress } from "antd";
import { Activity, AlertCircle, CheckCircle, Clock } from "lucide-react";
import { useNavigate } from "react-router";
import {formatExecutionDuration} from "@/utils/unit.ts";
export default function BasicInfo({ task }: { task: CleansingTask }) {
const navigate = useNavigate();
const descriptionItems = [
{
key: "id",
label: "任务ID",
children: <span className="font-mono">{task?.id}</span>,
},
{ key: "name", label: "任务名称", children: task?.name },
{
key: "dataset",
label: "源数据集",
children: (
<Button
style={{ paddingLeft: 0, marginLeft: 0 }}
type="link"
size="small"
onClick={() =>
navigate("/data/management/detail/" + task?.srcDatasetId)
}
>
{task?.srcDatasetName}
</Button>
),
},
{
key: "targetDataset",
label: "目标数据集",
children: (
<Button
style={{ paddingLeft: 0, marginLeft: 0 }}
type="link"
size="small"
onClick={() =>
navigate("/data/management/detail/" + task?.destDatasetId)
}
>
{task?.destDatasetName}
</Button>
),
},
{ key: "startTime", label: "开始时间", children: task?.startedAt },
{
key: "description",
label: "任务描述",
children: (
<span className="text-gray-600">{task?.description || "--"}</span>
),
span: 2,
},
];
return (
<>
{/* 执行摘要 */}
<Card className="mb-6">
<div className="grid grid-cols-4 gap-4">
<div className="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg">
<Clock className="w-8 h-8 text-blue-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-blue-500">
{formatExecutionDuration(task?.startedAt, task?.finishedAt) || "--"}
</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-lg">
<CheckCircle className="w-8 h-8 text-green-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-green-500">
{task?.progress?.succeedFileNum || "0"}
</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-lg">
<AlertCircle className="w-8 h-8 text-red-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-red-500">
{(task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress.failedFileNum :
task?.progress?.totalFileNum - task?.progress.succeedFileNum}
</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg">
<Activity className="w-8 h-8 text-purple-500 mb-2 mx-auto" />
<div className="text-xl font-bold text-purple-500">
{task?.progress?.successRate ? task?.progress?.successRate + "%" : "--"}
</div>
<div className="text-sm text-gray-600"></div>
</div>
</div>
</Card>
{/* 基本信息 */}
<Card>
<div className="mb-8">
<h3 className="text-lg font-semibold text-gray-900 mb-4"></h3>
<Descriptions
column={2}
bordered={false}
size="middle"
labelStyle={{ fontWeight: 500, color: "#555" }}
contentStyle={{ fontSize: 14 }}
items={descriptionItems}
></Descriptions>
</div>
{/* 处理进度 */}
<div>
<h3 className="text-lg font-semibold text-gray-900 mb-4"></h3>
{ task?.status?.value === TaskStatus.FAILED ?
<Progress percent={task?.progress?.process} size="small" status="exception" />
: <Progress percent={task?.progress?.process} size="small"/>
}
<div className="grid grid-cols-2 gap-4 text-sm mt-4">
<div className="flex items-center gap-2">
<span className="w-3 h-3 bg-green-500 rounded-full inline-block" />
<span>: {task?.progress?.succeedFileNum || "0"}</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 bg-blue-500 rounded-full inline-block" />
<span>: {(task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress?.totalFileNum - task?.progress.succeedFileNum : 0}</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 bg-red-500 rounded-full inline-block" />
<span>: {(task?.status.value === TaskStatus.RUNNING || task?.status.value === TaskStatus.PENDING) ?
task?.progress.failedFileNum :
task?.progress?.totalFileNum - task?.progress.succeedFileNum}</span>
</div>
</div>
</div>
</Card>
</>
);
}

View File

@@ -1,397 +1,397 @@
import {Button, Modal, Table, Badge, Input, Popover} from "antd";
import { Download } from "lucide-react";
import {useEffect, useState} from "react";
import {useParams} from "react-router";
import {TaskStatus} from "@/pages/DataCleansing/cleansing.model.ts";
import {TaskStatusMap} from "@/pages/DataCleansing/cleansing.const.tsx";
// 模拟文件列表数据
export default function FileTable({result, fetchTaskResult}) {
const { id = "" } = useParams();
const [showFileCompareDialog, setShowFileCompareDialog] = useState(false);
const [selectedFile, setSelectedFile] = useState<any>(null);
const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]);
useEffect(() => {
fetchTaskResult();
}, [id]);
const handleSelectAllFiles = (checked: boolean) => {
if (checked) {
setSelectedFileIds(result.map((file) => file.instanceId));
} else {
setSelectedFileIds([]);
}
};
const handleSelectFile = (fileId: string, checked: boolean) => {
if (checked) {
setSelectedFileIds([...selectedFileIds, fileId]);
} else {
setSelectedFileIds(selectedFileIds.filter((id) => id !== fileId));
}
};
const handleViewFileCompare = (file: any) => {
setSelectedFile(file);
setShowFileCompareDialog(true);
};
const handleBatchDownload = () => {
// 实际下载逻辑
};
function formatFileSize(bytes: number, decimals: number = 2): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];
}
const fileColumns = [
{
title: (
<input
type="checkbox"
checked={
selectedFileIds.length === result?.length && result?.length > 0
}
onChange={(e) => handleSelectAllFiles(e.target.checked)}
className="w-4 h-4"
/>
),
dataIndex: "select",
key: "select",
width: 50,
render: (_text: string, record: any) => (
<input
type="checkbox"
checked={selectedFileIds.includes(record.id)}
onChange={(e) => handleSelectFile(record.id, e.target.checked)}
className="w-4 h-4"
/>
),
},
{
title: "文件名",
dataIndex: "srcName",
key: "srcName",
width: 200,
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件名"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.srcName.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span>{text?.replace(/\.[^/.]+$/, "")}</span>
),
},
{
title: "清洗后文件名",
dataIndex: "destName",
key: "destName",
width: 200,
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件名"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.destName.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span>{text?.replace(/\.[^/.]+$/, "")}</span>
),
},
{
title: "文件类型",
dataIndex: "srcType",
key: "srcType",
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件类型"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.srcType.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span className="font-mono text-sm">{text}</span>
),
},
{
title: "清洗后文件类型",
dataIndex: "destType",
key: "destType",
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件类型"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.destType.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span className="font-mono text-sm">{text}</span>
),
},
{
title: "清洗前大小",
dataIndex: "srcSize",
key: "srcSize",
sorter: (a: any, b: any) => {
const getSizeInBytes = (size: string) => {
if (!size || size === "-") return 0;
const num = Number.parseFloat(size);
if (size.includes("GB")) return num * 1024 * 1024 * 1024;
if (size.includes("MB")) return num * 1024 * 1024;
if (size.includes("KB")) return num * 1024;
return num;
};
return getSizeInBytes(a.originalSize) - getSizeInBytes(b.originalSize);
},
render: (number: number) => (
<span className="font-mono text-sm">{formatFileSize(number)}</span>
),
},
{
title: "清洗后大小",
dataIndex: "destSize",
key: "destSize",
sorter: (a: any, b: any) => {
const getSizeInBytes = (size: string) => {
if (!size || size === "-") return 0;
const num = Number.parseFloat(size);
if (size.includes("GB")) return num * 1024 * 1024 * 1024;
if (size.includes("MB")) return num * 1024 * 1024;
if (size.includes("KB")) return num * 1024;
return num;
};
return (
getSizeInBytes(a.processedSize) - getSizeInBytes(b.processedSize)
);
},
render: (number: number) => (
<span className="font-mono text-sm">{formatFileSize(number)}</span>
),
},
{
title: "状态",
dataIndex: "status",
key: "status",
filters: [
{ text: "已完成", value: "COMPLETED" },
{ text: "失败", value: "FAILED" },
],
onFilter: (value: string, record: any) => record.status === value,
render: (status: string) => (
<Badge
status={
status === "COMPLETED"
? "success"
: "error"
}
text={TaskStatusMap[status as TaskStatus].label}
/>
),
},
{
title: "操作",
key: "action",
width: 200,
render: (_text: string, record: any) => (
<div className="flex">
{record.status === "COMPLETED" ? (
<Button
type="link"
size="small"
onClick={() => handleViewFileCompare(record)}
>
</Button>
) : (
<Button
type="link"
size="small"
disabled
>
</Button>
)}
<Popover content="暂未开放">
<Button type="link" size="small" disabled></Button>
</Popover>
</div>
),
},
];
return (
<>
{selectedFileIds.length > 0 && (
<div className="mb-4 flex justify-between">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-600">
{selectedFileIds.length}
</span>
<Button
onClick={handleBatchDownload}
size="small"
type="primary"
icon={<Download className="w-4 h-4 mr-2" />}
>
</Button>
</div>
</div>
)}
<Table
columns={fileColumns}
dataSource={result}
pagination={{ pageSize: 10, showSizeChanger: true }}
size="middle"
rowKey="id"
/>
{/* 文件对比弹窗 */}
<Modal
open={showFileCompareDialog}
onCancel={() => setShowFileCompareDialog(false)}
footer={null}
width={900}
title={<span> - {selectedFile?.fileName}</span>}
>
<div className="grid grid-cols-2 gap-6 py-6">
<div>
<h4 className="font-medium text-gray-900"></h4>
<div className="border border-gray-200 rounded-lg p-6 bg-gray-50 min-h-48 flex items-center justify-center">
<div className="text-center text-gray-500">
<div className="w-16 h-16 bg-gray-300 rounded-lg mx-auto mb-2" />
<div className="text-sm"></div>
<div className="text-xs text-gray-400">
: {formatFileSize(selectedFile?.srcSize)}
</div>
</div>
</div>
<div className="text-sm text-gray-600 mt-3 space-y-1">
<div>
<span className="font-medium">:</span> {selectedFile?.srcType}
</div>
</div>
</div>
<div>
<h4 className="font-medium text-gray-900"></h4>
<div className="border border-gray-200 rounded-lg p-6 bg-gray-50 min-h-48 flex items-center justify-center">
<div className="text-center text-gray-500">
<div className="w-16 h-16 bg-blue-300 rounded-lg mx-auto mb-2" />
<div className="text-sm"></div>
<div className="text-xs text-gray-400">
: {formatFileSize(selectedFile?.destSize)}
</div>
</div>
</div>
<div className="text-sm text-gray-600 mt-3 space-y-1">
<div>
<span className="font-medium">:</span> {selectedFile?.destType}
</div>
</div>
</div>
</div>
<div className="border-t border-gray-200 mt-6 pt-4">
<h4 className="font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-3 gap-4 text-sm">
<div className="bg-green-50 p-4 rounded-lg">
<div className="font-medium text-green-700"></div>
<div className="text-green-600"> {(100 * (selectedFile?.srcSize - selectedFile?.destSize) / selectedFile?.srcSize).toFixed(2)}%</div>
</div>
</div>
</div>
</Modal>
</>
);
}
import {Button, Modal, Table, Badge, Input, Popover} from "antd";
import { Download } from "lucide-react";
import {useEffect, useState} from "react";
import {useParams} from "react-router";
import {TaskStatus} from "@/pages/DataCleansing/cleansing.model.ts";
import {TaskStatusMap} from "@/pages/DataCleansing/cleansing.const.tsx";
// 模拟文件列表数据
export default function FileTable({result, fetchTaskResult}) {
const { id = "" } = useParams();
const [showFileCompareDialog, setShowFileCompareDialog] = useState(false);
const [selectedFile, setSelectedFile] = useState<any>(null);
const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]);
useEffect(() => {
fetchTaskResult();
}, [id]);
const handleSelectAllFiles = (checked: boolean) => {
if (checked) {
setSelectedFileIds(result.map((file) => file.instanceId));
} else {
setSelectedFileIds([]);
}
};
const handleSelectFile = (fileId: string, checked: boolean) => {
if (checked) {
setSelectedFileIds([...selectedFileIds, fileId]);
} else {
setSelectedFileIds(selectedFileIds.filter((id) => id !== fileId));
}
};
const handleViewFileCompare = (file: any) => {
setSelectedFile(file);
setShowFileCompareDialog(true);
};
const handleBatchDownload = () => {
// 实际下载逻辑
};
function formatFileSize(bytes: number, decimals: number = 2): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];
}
const fileColumns = [
{
title: (
<input
type="checkbox"
checked={
selectedFileIds.length === result?.length && result?.length > 0
}
onChange={(e) => handleSelectAllFiles(e.target.checked)}
className="w-4 h-4"
/>
),
dataIndex: "select",
key: "select",
width: 50,
render: (_text: string, record: any) => (
<input
type="checkbox"
checked={selectedFileIds.includes(record.id)}
onChange={(e) => handleSelectFile(record.id, e.target.checked)}
className="w-4 h-4"
/>
),
},
{
title: "文件名",
dataIndex: "srcName",
key: "srcName",
width: 200,
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件名"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.srcName.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span>{text?.replace(/\.[^/.]+$/, "")}</span>
),
},
{
title: "清洗后文件名",
dataIndex: "destName",
key: "destName",
width: 200,
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件名"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.destName.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span>{text?.replace(/\.[^/.]+$/, "")}</span>
),
},
{
title: "文件类型",
dataIndex: "srcType",
key: "srcType",
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件类型"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.srcType.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span className="font-mono text-sm">{text}</span>
),
},
{
title: "清洗后文件类型",
dataIndex: "destType",
key: "destType",
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}: any) => (
<div className="p-4 w-64">
<Input
placeholder="搜索文件类型"
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => confirm()}
className="mb-2"
/>
<div className="flex gap-2">
<Button size="small" onClick={() => confirm()}>
</Button>
<Button size="small" onClick={() => clearFilters()}>
</Button>
</div>
</div>
),
onFilter: (value: string, record: any) =>
record.destType.toLowerCase().includes(value.toLowerCase()),
render: (text: string) => (
<span className="font-mono text-sm">{text}</span>
),
},
{
title: "清洗前大小",
dataIndex: "srcSize",
key: "srcSize",
sorter: (a: any, b: any) => {
const getSizeInBytes = (size: string) => {
if (!size || size === "-") return 0;
const num = Number.parseFloat(size);
if (size.includes("GB")) return num * 1024 * 1024 * 1024;
if (size.includes("MB")) return num * 1024 * 1024;
if (size.includes("KB")) return num * 1024;
return num;
};
return getSizeInBytes(a.originalSize) - getSizeInBytes(b.originalSize);
},
render: (number: number) => (
<span className="font-mono text-sm">{formatFileSize(number)}</span>
),
},
{
title: "清洗后大小",
dataIndex: "destSize",
key: "destSize",
sorter: (a: any, b: any) => {
const getSizeInBytes = (size: string) => {
if (!size || size === "-") return 0;
const num = Number.parseFloat(size);
if (size.includes("GB")) return num * 1024 * 1024 * 1024;
if (size.includes("MB")) return num * 1024 * 1024;
if (size.includes("KB")) return num * 1024;
return num;
};
return (
getSizeInBytes(a.processedSize) - getSizeInBytes(b.processedSize)
);
},
render: (number: number) => (
<span className="font-mono text-sm">{formatFileSize(number)}</span>
),
},
{
title: "状态",
dataIndex: "status",
key: "status",
filters: [
{ text: "已完成", value: "COMPLETED" },
{ text: "失败", value: "FAILED" },
],
onFilter: (value: string, record: any) => record.status === value,
render: (status: string) => (
<Badge
status={
status === "COMPLETED"
? "success"
: "error"
}
text={TaskStatusMap[status as TaskStatus].label}
/>
),
},
{
title: "操作",
key: "action",
width: 200,
render: (_text: string, record: any) => (
<div className="flex">
{record.status === "COMPLETED" ? (
<Button
type="link"
size="small"
onClick={() => handleViewFileCompare(record)}
>
</Button>
) : (
<Button
type="link"
size="small"
disabled
>
</Button>
)}
<Popover content="暂未开放">
<Button type="link" size="small" disabled></Button>
</Popover>
</div>
),
},
];
return (
<>
{selectedFileIds.length > 0 && (
<div className="mb-4 flex justify-between">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-600">
{selectedFileIds.length}
</span>
<Button
onClick={handleBatchDownload}
size="small"
type="primary"
icon={<Download className="w-4 h-4 mr-2" />}
>
</Button>
</div>
</div>
)}
<Table
columns={fileColumns}
dataSource={result}
pagination={{ pageSize: 10, showSizeChanger: true }}
size="middle"
rowKey="id"
/>
{/* 文件对比弹窗 */}
<Modal
open={showFileCompareDialog}
onCancel={() => setShowFileCompareDialog(false)}
footer={null}
width={900}
title={<span> - {selectedFile?.fileName}</span>}
>
<div className="grid grid-cols-2 gap-6 py-6">
<div>
<h4 className="font-medium text-gray-900"></h4>
<div className="border border-gray-200 rounded-lg p-6 bg-gray-50 min-h-48 flex items-center justify-center">
<div className="text-center text-gray-500">
<div className="w-16 h-16 bg-gray-300 rounded-lg mx-auto mb-2" />
<div className="text-sm"></div>
<div className="text-xs text-gray-400">
: {formatFileSize(selectedFile?.srcSize)}
</div>
</div>
</div>
<div className="text-sm text-gray-600 mt-3 space-y-1">
<div>
<span className="font-medium">:</span> {selectedFile?.srcType}
</div>
</div>
</div>
<div>
<h4 className="font-medium text-gray-900"></h4>
<div className="border border-gray-200 rounded-lg p-6 bg-gray-50 min-h-48 flex items-center justify-center">
<div className="text-center text-gray-500">
<div className="w-16 h-16 bg-blue-300 rounded-lg mx-auto mb-2" />
<div className="text-sm"></div>
<div className="text-xs text-gray-400">
: {formatFileSize(selectedFile?.destSize)}
</div>
</div>
</div>
<div className="text-sm text-gray-600 mt-3 space-y-1">
<div>
<span className="font-medium">:</span> {selectedFile?.destType}
</div>
</div>
</div>
</div>
<div className="border-t border-gray-200 mt-6 pt-4">
<h4 className="font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-3 gap-4 text-sm">
<div className="bg-green-50 p-4 rounded-lg">
<div className="font-medium text-green-700"></div>
<div className="text-green-600"> {(100 * (selectedFile?.srcSize - selectedFile?.destSize) / selectedFile?.srcSize).toFixed(2)}%</div>
</div>
</div>
</div>
</Modal>
</>
);
}

View File

@@ -1,43 +1,43 @@
import {useEffect} from "react";
import {useParams} from "react-router";
import {FileClock} from "lucide-react";
export default function LogsTable({taskLog, fetchTaskLog} : {taskLog: any[], fetchTaskLog: () => Promise<any>}) {
const { id = "" } = useParams();
useEffect(() => {
fetchTaskLog();
}, [id]);
return taskLog?.length > 0 ? (
<>
<div className="text-gray-300 p-4 border border-gray-700 bg-gray-800 rounded-lg">
<div className="font-mono text-sm">
{taskLog?.map?.((log, index) => (
<div key={index} className="flex gap-3">
<span
className={`min-w-20 ${
log.level === "ERROR" || log.level === "FATAL"
? "text-red-500"
: log.level === "WARNING" || log.level === "WARN"
? "text-yellow-500"
: "text-green-500"
}`}
>
[{log.level}]
</span>
<span className="text-gray-100">{log.message}</span>
</div>
))}
</div>
</div>
</>
) : (
<div className="text-center py-12">
<FileClock className="w-16 h-16 text-gray-300 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">
</h3>
</div>
);
}
import {useEffect} from "react";
import {useParams} from "react-router";
import {FileClock} from "lucide-react";
export default function LogsTable({taskLog, fetchTaskLog} : {taskLog: any[], fetchTaskLog: () => Promise<any>}) {
const { id = "" } = useParams();
useEffect(() => {
fetchTaskLog();
}, [id]);
return taskLog?.length > 0 ? (
<>
<div className="text-gray-300 p-4 border border-gray-700 bg-gray-800 rounded-lg">
<div className="font-mono text-sm">
{taskLog?.map?.((log, index) => (
<div key={index} className="flex gap-3">
<span
className={`min-w-20 ${
log.level === "ERROR" || log.level === "FATAL"
? "text-red-500"
: log.level === "WARNING" || log.level === "WARN"
? "text-yellow-500"
: "text-green-500"
}`}
>
[{log.level}]
</span>
<span className="text-gray-100">{log.message}</span>
</div>
))}
</div>
</div>
</>
) : (
<div className="text-center py-12">
<FileClock className="w-16 h-16 text-gray-300 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">
</h3>
</div>
);
}

View File

@@ -1,25 +1,25 @@
import {Steps, Typography} from "antd";
import {useNavigate} from "react-router";
export default function OperatorTable({ task }: { task: any }) {
const navigate = useNavigate();
return task?.instance?.length > 0 && (
<>
<Steps
progressDot
direction="vertical"
items={Object.values(task?.instance).map((item) => ({
title: <Typography.Link
onClick={() => navigate(`/data/operator-market/plugin-detail/${item?.id}`)}
>
{item?.name}
</Typography.Link>,
description: item?.description,
status: "finish"
}))}
className="overflow-auto"
/>
</>
);
}
import {Steps, Typography} from "antd";
import {useNavigate} from "react-router";
export default function OperatorTable({ task }: { task: any }) {
const navigate = useNavigate();
return task?.instance?.length > 0 && (
<>
<Steps
progressDot
direction="vertical"
items={Object.values(task?.instance).map((item) => ({
title: <Typography.Link
onClick={() => navigate(`/data/operator-market/plugin-detail/${item?.id}`)}
>
{item?.name}
</Typography.Link>,
description: item?.description,
status: "finish"
}))}
className="overflow-auto"
/>
</>
);
}

View File

@@ -1,61 +1,61 @@
import { useEffect, useState } from "react";
import { Tabs, Button } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router";
import TaskList from "./components/TaskList";
import TemplateList from "./components/TemplateList";
import ProcessFlowDiagram from "./components/ProcessFlowDiagram";
import { useSearchParams } from "@/hooks/useSearchParams";
export default function DataProcessingPage() {
const navigate = useNavigate();
const urlParams = useSearchParams();
const [currentView, setCurrentView] = useState<"task" | "template">("task");
useEffect(() => {
if (urlParams.view) {
setCurrentView(urlParams.view);
}
}, [urlParams]);
return (
<div className="h-full flex flex-col gap-4">
{/* Header */}
<div className="flex justify-between items-center">
<h1 className="text-xl font-bold"></h1>
<div className="flex gap-2">
<Button
icon={<PlusOutlined />}
onClick={() => navigate("/data/cleansing/create-template")}
>
</Button>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => navigate("/data/cleansing/create-task")}
>
</Button>
</div>
</div>
<ProcessFlowDiagram />
<Tabs
activeKey={currentView}
onChange={(key) => setCurrentView(key as any)}
items={[
{
key: "task",
label: "任务列表",
},
{
key: "template",
label: "模板管理",
},
]}
/>
{currentView === "task" && <TaskList />}
{currentView === "template" && <TemplateList />}
</div>
);
}
import { useEffect, useState } from "react";
import { Tabs, Button } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router";
import TaskList from "./components/TaskList";
import TemplateList from "./components/TemplateList";
import ProcessFlowDiagram from "./components/ProcessFlowDiagram";
import { useSearchParams } from "@/hooks/useSearchParams";
export default function DataProcessingPage() {
const navigate = useNavigate();
const urlParams = useSearchParams();
const [currentView, setCurrentView] = useState<"task" | "template">("task");
useEffect(() => {
if (urlParams.view) {
setCurrentView(urlParams.view);
}
}, [urlParams]);
return (
<div className="h-full flex flex-col gap-4">
{/* Header */}
<div className="flex justify-between items-center">
<h1 className="text-xl font-bold"></h1>
<div className="flex gap-2">
<Button
icon={<PlusOutlined />}
onClick={() => navigate("/data/cleansing/create-template")}
>
</Button>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => navigate("/data/cleansing/create-task")}
>
</Button>
</div>
</div>
<ProcessFlowDiagram />
<Tabs
activeKey={currentView}
onChange={(key) => setCurrentView(key as any)}
items={[
{
key: "task",
label: "任务列表",
},
{
key: "template",
label: "模板管理",
},
]}
/>
{currentView === "task" && <TaskList />}
{currentView === "template" && <TemplateList />}
</div>
);
}

View File

@@ -1,86 +1,86 @@
import {
ArrowRight,
CheckCircle,
Database,
Play,
Settings,
Workflow,
Zap,
} from "lucide-react";
// 流程图组件
export default function ProcessFlowDiagram() {
const flowSteps = [
{
id: "start",
label: "开始",
type: "start",
icon: Play,
color: "bg-green-500",
},
{
id: "select",
label: "选择数据集",
type: "process",
icon: Database,
color: "bg-blue-500",
},
{
id: "config",
label: "基本配置",
type: "process",
icon: Settings,
color: "bg-purple-500",
},
{
id: "operators",
label: "算子编排",
type: "process",
icon: Workflow,
color: "bg-orange-500",
},
{
id: "execute",
label: "执行任务",
type: "process",
icon: Zap,
color: "bg-red-500",
},
{
id: "end",
label: "完成",
type: "end",
icon: CheckCircle,
color: "bg-green-500",
},
];
return (
<div className="border-card p-6">
<div className="w-full flex items-center justify-center">
<div className="w-full flex items-center space-x-12">
{flowSteps.map((step, index) => {
const IconComponent = step.icon;
return (
<div key={step.id} className="flex-1 flex items-center">
<div className="flex flex-col items-center w-full">
<div
className={`w-12 h-12 ${step.color} rounded-full flex items-center justify-center text-white shadow-lg`}
>
<IconComponent className="w-6 h-6" />
</div>
<span className="text-xs font-medium text-gray-700 mt-2 text-center max-w-16">
{step.label}
</span>
</div>
{index < flowSteps.length - 1 && (
<ArrowRight className="w-6 h-6 text-gray-400 mx-3" />
)}
</div>
);
})}
</div>
</div>
</div>
);
}
import {
ArrowRight,
CheckCircle,
Database,
Play,
Settings,
Workflow,
Zap,
} from "lucide-react";
// 流程图组件
export default function ProcessFlowDiagram() {
const flowSteps = [
{
id: "start",
label: "开始",
type: "start",
icon: Play,
color: "bg-green-500",
},
{
id: "select",
label: "选择数据集",
type: "process",
icon: Database,
color: "bg-blue-500",
},
{
id: "config",
label: "基本配置",
type: "process",
icon: Settings,
color: "bg-purple-500",
},
{
id: "operators",
label: "算子编排",
type: "process",
icon: Workflow,
color: "bg-orange-500",
},
{
id: "execute",
label: "执行任务",
type: "process",
icon: Zap,
color: "bg-red-500",
},
{
id: "end",
label: "完成",
type: "end",
icon: CheckCircle,
color: "bg-green-500",
},
];
return (
<div className="border-card p-6">
<div className="w-full flex items-center justify-center">
<div className="w-full flex items-center space-x-12">
{flowSteps.map((step, index) => {
const IconComponent = step.icon;
return (
<div key={step.id} className="flex-1 flex items-center">
<div className="flex flex-col items-center w-full">
<div
className={`w-12 h-12 ${step.color} rounded-full flex items-center justify-center text-white shadow-lg`}
>
<IconComponent className="w-6 h-6" />
</div>
<span className="text-xs font-medium text-gray-700 mt-2 text-center max-w-16">
{step.label}
</span>
</div>
{index < flowSteps.length - 1 && (
<ArrowRight className="w-6 h-6 text-gray-400 mx-3" />
)}
</div>
);
})}
</div>
</div>
</div>
);
}

View File

@@ -1,308 +1,308 @@
import { useState } from "react";
import { Table, Progress, Badge, Button, Tooltip, Card, App } from "antd";
import {
PlayCircleOutlined,
PauseCircleOutlined,
DeleteOutlined,
} from "@ant-design/icons";
import { SearchControls } from "@/components/SearchControls";
import CardView from "@/components/CardView";
import { useNavigate } from "react-router";
import { mapTask, TaskStatusMap } from "../../cleansing.const";
import {
TaskStatus,
type CleansingTask,
} from "@/pages/DataCleansing/cleansing.model";
import useFetchData from "@/hooks/useFetchData";
import {
deleteCleaningTaskByIdUsingDelete,
executeCleaningTaskUsingPost,
queryCleaningTasksUsingGet,
stopCleaningTaskUsingPost,
} from "../../cleansing.api";
export default function TaskList() {
const navigate = useNavigate();
const { message } = App.useApp();
const [viewMode, setViewMode] = useState<"card" | "list">("list");
const filterOptions = [
{
key: "status",
label: "状态",
options: [...Object.values(TaskStatusMap)],
},
];
const {
loading,
tableData,
pagination,
searchParams,
setSearchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryCleaningTasksUsingGet, mapTask);
const pauseTask = async (item: CleansingTask) => {
await stopCleaningTaskUsingPost(item.id);
message.success("任务已暂停");
fetchData();
};
const startTask = async (item: CleansingTask) => {
await executeCleaningTaskUsingPost(item.id);
message.success("任务已启动");
fetchData();
};
const deleteTask = async (item: CleansingTask) => {
await deleteCleaningTaskByIdUsingDelete(item.id);
message.success("任务已删除");
fetchData();
};
const taskOperations = (record: CleansingTask) => {
const isRunning = record.status?.value === TaskStatus.RUNNING;
const showStart = [
TaskStatus.PENDING,
TaskStatus.FAILED,
TaskStatus.STOPPED,
].includes(record.status?.value);
const pauseBtn = {
key: "pause",
label: "暂停",
icon: isRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />,
onClick: pauseTask, // implement pause/play logic
};
const startBtn = {
key: "start",
label: "启动",
icon: isRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />,
onClick: startTask, // implement pause/play logic
};
return [
...(isRunning
? [ pauseBtn ]
: []),
...(showStart
? [ startBtn ]
: []),
{
key: "delete",
label: "删除",
danger: true,
icon: <DeleteOutlined />,
onClick: deleteTask, // implement delete logic
},
];
};
const taskColumns = [
{
title: "任务名称",
dataIndex: "name",
key: "name",
fixed: "left",
width: 150,
ellipsis: true,
render: (_, task: CleansingTask) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/cleansing/task-detail/" + task.id)
}
>
{task.name}
</Button>
);
},
},
{
title: "任务ID",
dataIndex: "id",
key: "id",
width: 150,
ellipsis: true,
},
{
title: "源数据集",
dataIndex: "srcDatasetId",
key: "srcDatasetId",
width: 150,
ellipsis: true,
render: (_, record: CleansingTask) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/management/detail/" + record.srcDatasetId)
}
>
{record.srcDatasetName}
</Button>
);
},
},
{
title: "目标数据集",
dataIndex: "destDatasetId",
key: "destDatasetId",
width: 150,
ellipsis: true,
render: (_, record: CleansingTask) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/management/detail/" + record.destDatasetId)
}
>
{record.destDatasetName}
</Button>
);
},
},
{
title: "状态",
dataIndex: "status",
key: "status",
width: 100,
render: (status: any) => {
return <Badge color={status?.color} text={status?.label} />;
},
},
{
title: "进度",
dataIndex: "process",
key: "process",
width: 150,
render: (_, record: CleansingTask) => {
if (record?.status?.value == TaskStatus.FAILED) {
return <Progress percent={record?.progress?.process} size="small" status="exception" />;
}
return <Progress percent={record?.progress?.process} size="small"/>;
},
},
{
title: "已处理文件数",
dataIndex: "finishedFileNum",
key: "finishedFileNum",
width: 120,
align: "right",
ellipsis: true,
},
{
title: "总文件数",
dataIndex: "totalFileNum",
key: "totalFileNum",
width: 100,
align: "right",
ellipsis: true,
},
{
title: "执行耗时",
dataIndex: "duration",
key: "duration",
width: 100,
ellipsis: true,
},
{
title: "开始时间",
dataIndex: "startedAt",
key: "startedAt",
width: 180,
ellipsis: true,
},
{
title: "结束时间",
dataIndex: "finishedAt",
key: "finishedAt",
width: 180,
ellipsis: true,
},
{
title: "创建时间",
dataIndex: "createdAt",
key: "createdAt",
width: 180,
ellipsis: true,
},
{
title: "数据量变化",
dataIndex: "dataSizeChange",
key: "dataSizeChange",
width: 180,
ellipsis: true,
render: (_: any, record: CleansingTask) => {
if (record.before !== undefined && record.after !== undefined) {
return `${record.before}${record.after}`;
}
return "-";
},
},
{
title: "操作",
key: "action",
fixed: "right",
render: (text: string, record: any) => (
<div className="flex gap-2">
{taskOperations(record).map((op) =>
op ? (
<Tooltip key={op.key} title={op.label}>
<Button
type="text"
icon={op.icon}
danger={op?.danger}
onClick={() => op.onClick(record)}
/>
</Tooltip>
) : null
)}
</div>
),
},
];
return (
<>
{/* Search and Filters */}
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索任务名称、描述"
filters={filterOptions}
onFiltersChange={handleFiltersChange}
viewMode={viewMode}
onViewModeChange={setViewMode}
showViewToggle={true}
onReload={fetchData}
onClearFilters={() => setSearchParams({ ...searchParams, filter: {} })}
/>
{/* Task List */}
{viewMode === "card" ? (
<CardView
data={tableData}
operations={taskOperations}
pagination={pagination}
onView={(tableData) => {
navigate("/data/cleansing/task-detail/" + tableData.id)
}}
/>
) : (
<Card>
<Table
columns={taskColumns}
dataSource={tableData}
rowKey="id"
loading={loading}
scroll={{ x: "max-content", y: "calc(100vh - 35rem)" }}
pagination={pagination}
/>
</Card>
)}
</>
);
}
import { useState } from "react";
import { Table, Progress, Badge, Button, Tooltip, Card, App } from "antd";
import {
PlayCircleOutlined,
PauseCircleOutlined,
DeleteOutlined,
} from "@ant-design/icons";
import { SearchControls } from "@/components/SearchControls";
import CardView from "@/components/CardView";
import { useNavigate } from "react-router";
import { mapTask, TaskStatusMap } from "../../cleansing.const";
import {
TaskStatus,
type CleansingTask,
} from "@/pages/DataCleansing/cleansing.model";
import useFetchData from "@/hooks/useFetchData";
import {
deleteCleaningTaskByIdUsingDelete,
executeCleaningTaskUsingPost,
queryCleaningTasksUsingGet,
stopCleaningTaskUsingPost,
} from "../../cleansing.api";
export default function TaskList() {
const navigate = useNavigate();
const { message } = App.useApp();
const [viewMode, setViewMode] = useState<"card" | "list">("list");
const filterOptions = [
{
key: "status",
label: "状态",
options: [...Object.values(TaskStatusMap)],
},
];
const {
loading,
tableData,
pagination,
searchParams,
setSearchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryCleaningTasksUsingGet, mapTask);
const pauseTask = async (item: CleansingTask) => {
await stopCleaningTaskUsingPost(item.id);
message.success("任务已暂停");
fetchData();
};
const startTask = async (item: CleansingTask) => {
await executeCleaningTaskUsingPost(item.id);
message.success("任务已启动");
fetchData();
};
const deleteTask = async (item: CleansingTask) => {
await deleteCleaningTaskByIdUsingDelete(item.id);
message.success("任务已删除");
fetchData();
};
const taskOperations = (record: CleansingTask) => {
const isRunning = record.status?.value === TaskStatus.RUNNING;
const showStart = [
TaskStatus.PENDING,
TaskStatus.FAILED,
TaskStatus.STOPPED,
].includes(record.status?.value);
const pauseBtn = {
key: "pause",
label: "暂停",
icon: isRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />,
onClick: pauseTask, // implement pause/play logic
};
const startBtn = {
key: "start",
label: "启动",
icon: isRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />,
onClick: startTask, // implement pause/play logic
};
return [
...(isRunning
? [ pauseBtn ]
: []),
...(showStart
? [ startBtn ]
: []),
{
key: "delete",
label: "删除",
danger: true,
icon: <DeleteOutlined />,
onClick: deleteTask, // implement delete logic
},
];
};
const taskColumns = [
{
title: "任务名称",
dataIndex: "name",
key: "name",
fixed: "left",
width: 150,
ellipsis: true,
render: (_, task: CleansingTask) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/cleansing/task-detail/" + task.id)
}
>
{task.name}
</Button>
);
},
},
{
title: "任务ID",
dataIndex: "id",
key: "id",
width: 150,
ellipsis: true,
},
{
title: "源数据集",
dataIndex: "srcDatasetId",
key: "srcDatasetId",
width: 150,
ellipsis: true,
render: (_, record: CleansingTask) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/management/detail/" + record.srcDatasetId)
}
>
{record.srcDatasetName}
</Button>
);
},
},
{
title: "目标数据集",
dataIndex: "destDatasetId",
key: "destDatasetId",
width: 150,
ellipsis: true,
render: (_, record: CleansingTask) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/management/detail/" + record.destDatasetId)
}
>
{record.destDatasetName}
</Button>
);
},
},
{
title: "状态",
dataIndex: "status",
key: "status",
width: 100,
render: (status: any) => {
return <Badge color={status?.color} text={status?.label} />;
},
},
{
title: "进度",
dataIndex: "process",
key: "process",
width: 150,
render: (_, record: CleansingTask) => {
if (record?.status?.value == TaskStatus.FAILED) {
return <Progress percent={record?.progress?.process} size="small" status="exception" />;
}
return <Progress percent={record?.progress?.process} size="small"/>;
},
},
{
title: "已处理文件数",
dataIndex: "finishedFileNum",
key: "finishedFileNum",
width: 120,
align: "right",
ellipsis: true,
},
{
title: "总文件数",
dataIndex: "totalFileNum",
key: "totalFileNum",
width: 100,
align: "right",
ellipsis: true,
},
{
title: "执行耗时",
dataIndex: "duration",
key: "duration",
width: 100,
ellipsis: true,
},
{
title: "开始时间",
dataIndex: "startedAt",
key: "startedAt",
width: 180,
ellipsis: true,
},
{
title: "结束时间",
dataIndex: "finishedAt",
key: "finishedAt",
width: 180,
ellipsis: true,
},
{
title: "创建时间",
dataIndex: "createdAt",
key: "createdAt",
width: 180,
ellipsis: true,
},
{
title: "数据量变化",
dataIndex: "dataSizeChange",
key: "dataSizeChange",
width: 180,
ellipsis: true,
render: (_: any, record: CleansingTask) => {
if (record.before !== undefined && record.after !== undefined) {
return `${record.before}${record.after}`;
}
return "-";
},
},
{
title: "操作",
key: "action",
fixed: "right",
render: (text: string, record: any) => (
<div className="flex gap-2">
{taskOperations(record).map((op) =>
op ? (
<Tooltip key={op.key} title={op.label}>
<Button
type="text"
icon={op.icon}
danger={op?.danger}
onClick={() => op.onClick(record)}
/>
</Tooltip>
) : null
)}
</div>
),
},
];
return (
<>
{/* Search and Filters */}
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索任务名称、描述"
filters={filterOptions}
onFiltersChange={handleFiltersChange}
viewMode={viewMode}
onViewModeChange={setViewMode}
showViewToggle={true}
onReload={fetchData}
onClearFilters={() => setSearchParams({ ...searchParams, filter: {} })}
/>
{/* Task List */}
{viewMode === "card" ? (
<CardView
data={tableData}
operations={taskOperations}
pagination={pagination}
onView={(tableData) => {
navigate("/data/cleansing/task-detail/" + tableData.id)
}}
/>
) : (
<Card>
<Table
columns={taskColumns}
dataSource={tableData}
rowKey="id"
loading={loading}
scroll={{ x: "max-content", y: "calc(100vh - 35rem)" }}
pagination={pagination}
/>
</Card>
)}
</>
);
}

View File

@@ -1,156 +1,156 @@
import {DeleteOutlined, EditOutlined} from "@ant-design/icons";
import CardView from "@/components/CardView";
import {
deleteCleaningTemplateByIdUsingDelete, queryCleaningTemplatesUsingGet,
} from "../../cleansing.api";
import useFetchData from "@/hooks/useFetchData";
import {mapTemplate} from "../../cleansing.const";
import {App, Button, Card, Table, Tooltip} from "antd";
import {CleansingTemplate} from "../../cleansing.model";
import {SearchControls} from "@/components/SearchControls.tsx";
import {useNavigate} from "react-router";
import {useState} from "react";
export default function TemplateList() {
const navigate = useNavigate();
const { message } = App.useApp();
const [viewMode, setViewMode] = useState<"card" | "list">("list");
const {
loading,
tableData,
pagination,
searchParams,
setSearchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryCleaningTemplatesUsingGet, mapTemplate);
const templateOperations = () => {
return [
{
key: "update",
label: "编辑",
icon: <EditOutlined />,
onClick: (template: CleansingTemplate) => navigate(`/data/cleansing/update-template/${template.id}`)
},
{
key: "delete",
label: "删除",
danger: true,
icon: <DeleteOutlined />,
onClick: deleteTemplate, // implement delete logic
},
];
};
const templateColumns = [
{
title: "模板名称",
dataIndex: "name",
key: "name",
fixed: "left",
width: 150,
ellipsis: true,
render: (_, template: CleansingTemplate) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/cleansing/template-detail/" + template.id)
}
>
{template.name}
</Button>
);
}},
{
title: "模板ID",
dataIndex: "id",
key: "id",
fixed: "left",
width: 150,
},
{
title: "算子数量",
dataIndex: "num",
key: "num",
width: 100,
ellipsis: true,
render: (_, template: CleansingTemplate) => {
return template.instance?.length ?? 0;
},
},
{
title: "操作",
key: "action",
fixed: "right",
width: 20,
render: (text: string, record: any) => (
<div className="flex gap-2">
{templateOperations(record).map((op) =>
op ? (
<Tooltip key={op.key} title={op.label}>
<Button
type="text"
icon={op.icon}
danger={op?.danger}
onClick={() => op.onClick(record)}
/>
</Tooltip>
) : null
)}
</div>
),
},
]
const deleteTemplate = async (template: CleansingTemplate) => {
if (!template.id) {
return;
}
// 实现删除逻辑
await deleteCleaningTemplateByIdUsingDelete(template.id);
fetchData();
message.success("模板删除成功");
};
return (
<>
{/* Search and Filters */}
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索模板名称、描述"
onFiltersChange={handleFiltersChange}
viewMode={viewMode}
onViewModeChange={setViewMode}
showViewToggle={true}
onReload={fetchData}
onClearFilters={() => setSearchParams({ ...searchParams, filter: {} })}
/>
{viewMode === "card" ? (
<CardView
data={tableData}
operations={templateOperations}
pagination={pagination}
onView={(tableData) => {
navigate("/data/cleansing/template-detail/" + tableData.id)
}}
/>
) : (
<Card>
<Table
columns={templateColumns}
dataSource={tableData}
rowKey="id"
loading={loading}
scroll={{ x: "max-content", y: "calc(100vh - 35rem)" }}
pagination={pagination}
/>
</Card>
)}
</>
);
}
import {DeleteOutlined, EditOutlined} from "@ant-design/icons";
import CardView from "@/components/CardView";
import {
deleteCleaningTemplateByIdUsingDelete, queryCleaningTemplatesUsingGet,
} from "../../cleansing.api";
import useFetchData from "@/hooks/useFetchData";
import {mapTemplate} from "../../cleansing.const";
import {App, Button, Card, Table, Tooltip} from "antd";
import {CleansingTemplate} from "../../cleansing.model";
import {SearchControls} from "@/components/SearchControls.tsx";
import {useNavigate} from "react-router";
import {useState} from "react";
export default function TemplateList() {
const navigate = useNavigate();
const { message } = App.useApp();
const [viewMode, setViewMode] = useState<"card" | "list">("list");
const {
loading,
tableData,
pagination,
searchParams,
setSearchParams,
fetchData,
handleFiltersChange,
handleKeywordChange,
} = useFetchData(queryCleaningTemplatesUsingGet, mapTemplate);
const templateOperations = () => {
return [
{
key: "update",
label: "编辑",
icon: <EditOutlined />,
onClick: (template: CleansingTemplate) => navigate(`/data/cleansing/update-template/${template.id}`)
},
{
key: "delete",
label: "删除",
danger: true,
icon: <DeleteOutlined />,
onClick: deleteTemplate, // implement delete logic
},
];
};
const templateColumns = [
{
title: "模板名称",
dataIndex: "name",
key: "name",
fixed: "left",
width: 150,
ellipsis: true,
render: (_, template: CleansingTemplate) => {
return (
<Button
type="link"
onClick={() =>
navigate("/data/cleansing/template-detail/" + template.id)
}
>
{template.name}
</Button>
);
}},
{
title: "模板ID",
dataIndex: "id",
key: "id",
fixed: "left",
width: 150,
},
{
title: "算子数量",
dataIndex: "num",
key: "num",
width: 100,
ellipsis: true,
render: (_, template: CleansingTemplate) => {
return template.instance?.length ?? 0;
},
},
{
title: "操作",
key: "action",
fixed: "right",
width: 20,
render: (text: string, record: any) => (
<div className="flex gap-2">
{templateOperations(record).map((op) =>
op ? (
<Tooltip key={op.key} title={op.label}>
<Button
type="text"
icon={op.icon}
danger={op?.danger}
onClick={() => op.onClick(record)}
/>
</Tooltip>
) : null
)}
</div>
),
},
]
const deleteTemplate = async (template: CleansingTemplate) => {
if (!template.id) {
return;
}
// 实现删除逻辑
await deleteCleaningTemplateByIdUsingDelete(template.id);
fetchData();
message.success("模板删除成功");
};
return (
<>
{/* Search and Filters */}
<SearchControls
searchTerm={searchParams.keyword}
onSearchChange={handleKeywordChange}
searchPlaceholder="搜索模板名称、描述"
onFiltersChange={handleFiltersChange}
viewMode={viewMode}
onViewModeChange={setViewMode}
showViewToggle={true}
onReload={fetchData}
onClearFilters={() => setSearchParams({ ...searchParams, filter: {} })}
/>
{viewMode === "card" ? (
<CardView
data={tableData}
operations={templateOperations}
pagination={pagination}
onView={(tableData) => {
navigate("/data/cleansing/template-detail/" + tableData.id)
}}
/>
) : (
<Card>
<Table
columns={templateColumns}
dataSource={tableData}
rowKey="id"
loading={loading}
scroll={{ x: "max-content", y: "calc(100vh - 35rem)" }}
pagination={pagination}
/>
</Card>
)}
</>
);
}

Some files were not shown because too many files have changed in this diff Show More