# 组件规范

> 适用范围: React 19 + TypeScript 6 + Ant Design 6 + ProComponents
> 版本: v3.3

---

## 1、React 组件规范

### 1.1 函数组件结构

```tsx
// 1. 导入语句（按类型分组：React -> 第三方库 -> 本地模块 -> 样式）
import { useState, useEffect, useCallback, useRef } from 'react';
import { Form, Table, Button, Modal, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ProTable, type ProColumns, type ActionType } from '@ant-design/pro-components';
import { getUserList, deleteUser } from '@/api/system/user';
import type { User } from '@/types/system/user';
import Access from '@/components/Access';

// 2. 类型定义（复杂类型建议放在 src/types/ 下）
interface UserListProps {
  departmentId?: number;
}

// 3. 组件定义（使用 function 声明）
export default function UserList({ departmentId }: UserListProps) {
  // 4. Hooks 调用（按顺序：ref/state -> custom hooks -> effects）
  const { message, modal } = App.useApp();
  const actionRef = useRef<ActionType>(undefined);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 5. 事件处理函数
  const handleDelete = useCallback(async (record: User) => {
    modal.confirm({
      title: '确认删除？',
      okType: 'danger',
      content: `确认删除「${record.name}」吗？`,
      onOk: async () => {
        await deleteUser(record.id!);
        message.success('删除成功');
        actionRef.current?.reload();
      },
    });
  }, [message, modal]);

  // 6. 列定义
  const columns: ProColumns<User>[] = [
    { title: '名称', dataIndex: 'name', width: 200 },
    { title: '操作', key: 'action', search: false, render: (_, record) => (
      <Space>
        <Access code="system:user:update">
          <a onClick={() => handleEdit(record)}>编辑</a>
        </Access>
        <Access code="system:user:delete">
          <a style={{ color: '#ff4d4f' }} onClick={() => handleDelete(record)}>删除</a>
        </Access>
      </Space>
    )},
  ];

  // 7. 渲染
  return (
    <ProTable<User>
      columns={columns}
      actionRef={actionRef}
      rowKey="id"
      request={async (params) => {
        const { current, pageSize, ...rest } = params;
        const { data } = await getUserList({ pageNo: current, pageSize, ...rest });
        return { data: data.list, total: data.total, success: true };
      }}
      toolBarRender={() => [
        <Access code="system:user:create" key="add">
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增</Button>
        </Access>,
      ]}
    />
  );
}
```

### 1.2 Props 定义

```typescript
// 使用 interface 定义 props
interface UserCardProps {
  user: User;                        // 必填
  showActions?: boolean;             // 可选
  size?: 'small' | 'medium' | 'large'; // 带默认值
  onDelete: (id: number) => void;    // 回调
  children?: React.ReactNode;        // 子组件
}

// 使用 destructuring + 默认值
export default function UserCard({
  user,
  showActions = false,
  size = 'medium',
  onDelete,
  children,
}: UserCardProps) {
  return <div>{/* ... */}</div>;
}
```

### 1.3 组件拆分原则

- 单个组件不超过 300 行，超出按职责拆分
- 页面内的子组件（Modal、Drawer 等）放在 `src/pages/<feature>/components/` 目录
- 全局复用组件放在 `src/components/`
- 避免在组件内部定义类型，应放在 `src/types/` 目录

### 1.4 自定义 Hook 规范

```typescript
// hooks/useAccess.ts — 以 use 开头
import { useAuthStore } from '@/stores/useAuthStore';

export function useAccess(code: string): boolean {
  const hasPermission = useAuthStore((s) => s.hasPermission);
  return hasPermission(code);
}
```

---


---

## 2、上传组件规范

### 2.1 标准用法

```tsx
import { Upload } from 'antd';
import { getAccessToken } from '@/utils/token';
import { useAuthStore } from '@/stores/useAuthStore';

<Upload
  name="file"
  action="/admin-api/infra/file/upload"
  headers={{
    Authorization: `Bearer ${getAccessToken() ?? ''}`,
    'tenant-id': String(useAuthStore.getState().tenantId ?? ''),
  }}
  beforeUpload={...}
  onChange={({ file }) => {
    if (file.status === 'done') {
      const resp = file.response as { code?: number; data?: string };
      if (resp?.code === 0 && resp.data) {
        form.setFieldsValue({ avatar: resp.data });
      }
    }
  }}
/>
```

或直接使用项目封装：`import { UploadFile, UploadImg, UploadImgs } from '@/components/UploadFile'`。

### 2.2 Upload 在 Form 中的正确使用

> AntD `Upload` 不识别 `value` 属性。`<Form.Item name="logo">` 默认会注入 `value` → Upload 报警告。

**正确做法**：外层 `Form.Item` 仅做标签（不带 `name`），里面套一个 `<Form.Item name="logo" noStyle hidden><Input /></Form.Item>` 持有值，Upload 通过 `form.setFieldsValue({ logo: url })` 写入。

---

## 3、时间格式化规范

**统一使用 `dateFormatter`**，禁止页面内手写 `dayjs().format(...)` 或字符串拼接：

```tsx
import { dateFormatter } from '@/utils/formatTime';

// ProTable 列
render: (_, record) => dateFormatter(record.createTime) || '-',

// Descriptions
<Descriptions.Item label="创建时间">{dateFormatter(data.createTime) || '-'}</Descriptions.Item>
```

`dateFormatter` 接受 `string | number | Date | null`，统一返回 `YYYY-MM-DD HH:mm:ss`，空值返回空串。

> **注意**：如果后端 `createTime` 可能是 number/Date，统一用 `new Date(value).getTime()` 包装再比较。

---

## 4、<Alert />组件使用规范

- Ant Design 6 中 `Alert` 的 `message` 属性已弃用，控制台报 `[antd: Alert] message is deprecated. Please use title instead.`
- **严禁**写 `<Alert message="..." />`，**必须**改为 `<Alert title="..." />`
- 全仓库排查命令：`grep -rn "Alert" web-ui/src --include="*.tsx" | grep "message="`
- 已清理范围：本体模块（detail 编辑锁提示条、BindingTab、GraphTab、CleanupModal、VersionDiffDrawer、YamlTab 等）——新增代码必须遵守，勿让该警告回潮
