npm package: @kwayteow/schema-antd-form
Description: 一个基于 Formily + Ant Design 的强大 Schema 表单组件库，提供开箱即用的表单解决方案。
Latest version: 0.0.1

# @kwayteow/schema-antd-form

一个基于 Formily + Ant Design 的强大 Schema 表单组件库，提供开箱即用的表单解决方案。

[![npm version](https://badge.fury.io/js/@kwayteow%2Fschema-antd-form.svg)](https://badge.fury.io/js/@kwayteow%2Fschema-antd-form)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## ✨ 特性

- 🚀 **开箱即用** - 基于 JSON Schema 快速构建复杂表单
- 🎨 **丰富组件** - 内置所有 Ant Design 表单组件
- 🔄 **异步支持** - 完整的异步数据加载和字段联动
- 🎯 **预设配置** - 多种表单布局和行为预设
- 🛡️ **类型安全** - 完整的 TypeScript 支持
- 🔧 **高度可定制** - 灵活的配置和扩展能力
- 📱 **响应式** - 支持多种屏幕尺寸
- 🌐 **国际化** - 支持多语言

## 📦 安装

```bash
npm install @kwayteow/schema-antd-form
# 或
yarn add @kwayteow/schema-antd-form
# 或
pnpm add @kwayteow/schema-antd-form
```

### 依赖要求

```json
{
  "react": ">=18.0.0",
  "react-dom": ">=18.0.0",
  "antd": ">=5.0.0",
  "@formily/core": ">=2.3.0",
  "@formily/react": ">=2.3.0"
}
```

## 🚀 快速开始

### 基础用法

```tsx
import React from "react";
import { SchemaForm } from "@kwayteow/schema-antd-form";

const App = () => {
  const schema = {
    type: "object",
    properties: {
      name: {
        type: "string",
        title: "姓名",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Input",
      },
      email: {
        type: "string",
        title: "邮箱",
        "x-decorator": "FormItem",
        "x-component": "Input",
        "x-validator": [{ format: "email" }],
      },
      submit: {
        type: "void",
        "x-component": "Submit",
        "x-component-props": {
          children: "提交",
        },
      },
    },
  };

  return (
    <SchemaForm
      schema={schema}
      events={{
        onFormSubmitSuccess: (values) => {
          console.log("提交成功:", values);
        },
      }}
    />
  );
};
```

### 使用预设配置

```tsx
import { SchemaForm, createFormWithPreset } from "@kwayteow/schema-antd-form";

const LoginForm = () => {
  const config = createFormWithPreset("login", {
    events: {
      onFormSubmitSuccess: (values) => {
        console.log("登录成功:", values);
      },
    },
  });

  return <SchemaForm {...config} schema={loginSchema} />;
};
```

### API 集成

```tsx
import { SchemaForm, HttpService } from "@kwayteow/schema-antd-form";

const FormWithAPI = () => {
  const httpClient = new HttpService("https://api.example.com");

  return (
    <SchemaForm
      schema={schema}
      httpClient={httpClient}
      api={{
        url: "/users",
        method: "POST",
      }}
      events={{
        onFormSubmitSuccess: (result) => {
          console.log("API 响应:", result);
        },
        onFormSubmitFailed: (error) => {
          console.error("提交失败:", error);
        },
      }}
    />
  );
};
```

## 📚 核心概念

### SchemaForm 组件

主要的表单组件，支持以下配置：

```tsx
interface SchemaFormProps {
  schema: Record<string, unknown>; // 表单 Schema 定义
  ui?: UIConfig; // UI 配置
  api?: RequestOptions | Function; // API 配置
  httpClient?: HttpClient; // HTTP 客户端
  events?: EventConfig; // 事件回调
  lifecycle?: LifecycleConfig; // 生命周期
  initialValues?: any; // 初始值
  // ... 其他 Formily 配置
}
```

### UI 配置

支持多种布局和样式配置：

```tsx
// 简单配置
const ui = {
  layout: "horizontal",
  size: "middle",
  disabled: false,
};

// 完整配置
const ui = {
  layout: "horizontal",
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
  labelAlign: "right",
  size: "large",
  style: { padding: "20px" },
};
```

### 预设配置

内置多种常用表单预设：

- `vertical` - 垂直布局，适合移动端
- `horizontal` - 水平布局，适合桌面端
- `inline` - 内联布局，适合搜索表单
- `compact` - 紧凑布局，节省空间
- `large` - 大尺寸布局

```tsx
import { uiPresets, createFormWithPreset } from '@kwayteow/schema-antd-form'

// 使用 UI 预设
<SchemaForm ui={uiPresets.horizontal} schema={schema} />

// 使用表单预设
const config = createFormWithPreset('login')
<SchemaForm {...config} schema={schema} />
```

## 🔄 异步功能

### 异步数据源

```tsx
import { updateAsyncDataSource } from "@kwayteow/schema-antd-form";
import { onFieldValueChange } from "@formily/core";

<SchemaForm
  schema={schema}
  effects={(form) => {
    onFieldValueChange("province", async (field) => {
      const cityField = form.query("city").take();
      await updateAsyncDataSource(
        cityField,
        async (field) => {
          const cities = await getCitiesByProvince(field.form.values.province);
          return cities;
        },
        {
          onSuccess: () => console.log("城市加载完成"),
          onError: (error) => console.error("加载失败:", error),
        }
      );
    });
  }}
/>;
```

### 异步字段联动

```tsx
import { updateAsyncValue } from "@kwayteow/schema-antd-form";

// 用户信息自动填充
onFieldValueChange("userId", async (field) => {
  await updateAsyncValue(field, async (field) => {
    const userInfo = await getUserInfo(field.value);
    // 自动填充其他字段
    const nameField = form.query("name").take();
    nameField.setValue(userInfo.name);
    return userInfo;
  });
});
```

### 权限控制

```tsx
import { updateAsyncFieldProps } from "@kwayteow/schema-antd-form";

// 根据角色控制字段权限
onFieldValueChange("role", async (field) => {
  const sensitiveField = form.query("sensitiveData").take();
  await updateAsyncFieldProps(sensitiveField, async (field) => {
    const permission = await getPermission(field.form.values.role);
    return {
      required: permission.required,
      disabled: permission.disabled,
    };
  });
});
```

## 🛠️ 可用组件

### 表单组件

- `Input` - 输入框
- `Input.TextArea` - 文本域
- `Input.Password` - 密码框
- `InputNumber` - 数字输入框
- `Select` - 选择器
- `Checkbox` - 复选框
- `Radio` - 单选框
- `Switch` - 开关
- `DatePicker` - 日期选择器
- `TimePicker` - 时间选择器
- `Upload` - 文件上传
- `Rate` - 评分
- `Slider` - 滑动输入条

### 布局组件

- `FormItem` - 表单项
- `FormLayout` - 表单布局
- `Submit` - 提交按钮

## 🔧 异步函数 API

| 函数名                         | 描述             | 用途                 |
| ------------------------------ | ---------------- | -------------------- |
| `updateAsyncDataSource`        | 异步更新数据源   | 下拉框选项、级联数据 |
| `updateAsyncValue`             | 异步更新字段值   | 自动填充、计算值     |
| `updateAsyncFieldProps`        | 异步更新字段属性 | 权限控制、动态验证   |
| `updateAsyncComponentProps`    | 异步更新组件属性 | 动态样式、配置       |
| `updateAsyncFieldLinkage`      | 异步字段联动     | 复杂联动逻辑         |
| `updateAsyncConditionalRender` | 异步条件渲染     | 动态显示/隐藏        |
| `updateAsyncForm`              | 异步表单更新     | 整体状态变更         |

## 📖 高级用法

### 错误处理

```tsx
<SchemaForm
  schema={schema}
  events={{
    onFormSubmitFailed: (error) => {
      switch (error.type) {
        case "validation":
          message.error("表单验证失败");
          break;
        case "network":
          message.error("网络请求失败");
          break;
        case "business":
          message.error(`业务错误: ${error.message}`);
          break;
        default:
          message.error("未知错误");
      }
    },
  }}
/>
```

### 自定义 HTTP 客户端

```tsx
import { HttpService } from '@kwayteow/schema-antd-form'

const customHttpClient = new HttpService('https://api.example.com', {
  headers: {
    'Authorization': 'Bearer your-token',
    'X-API-Key': 'your-api-key',
  },
  timeout: 10000,
})

<SchemaForm httpClient={customHttpClient} />
```

### 生命周期管理

```tsx
<SchemaForm
  schema={schema}
  lifecycle={{
    onFormMount: (values, form) => {
      console.log("表单挂载");
    },
    onFormValuesChange: (values, form) => {
      // 自动保存草稿
      localStorage.setItem("draft", JSON.stringify(values));
    },
  }}
/>
```

## 🎨 主题定制

组件完全兼容 Ant Design 的主题系统：

```tsx
import { ConfigProvider } from "antd";

<ConfigProvider
  theme={{
    token: {
      colorPrimary: "#1890ff",
    },
  }}
>
  <SchemaForm schema={schema} />
</ConfigProvider>;
```

## 📝 Schema 规范

基于 JSON Schema 标准，扩展了 Formily 的 x- 属性：

```json
{
  "type": "object",
  "properties": {
    "fieldName": {
      "type": "string",
      "title": "字段标题",
      "description": "字段描述",
      "required": true,
      "x-decorator": "FormItem",
      "x-component": "Input",
      "x-component-props": {
        "placeholder": "请输入"
      },
      "x-validator": [
        {
          "required": true,
          "message": "此字段为必填项"
        }
      ]
    }
  }
}
```

## 🤝 贡献指南

我们欢迎所有形式的贡献！

### 开发环境

```bash
# 克隆项目
git clone https://github.com/kway-teow/schema-antd-form.git

# 安装依赖
npm install

# 启动开发服务器
npm run dev

# 启动文档
npm run doc
```

### 提交规范

请遵循 [Conventional Commits](https://conventionalcommits.org/) 规范：

```
feat: 添加新功能
fix: 修复问题
docs: 更新文档
style: 代码格式调整
refactor: 代码重构
test: 添加测试
chore: 构建过程或辅助工具的变动
```

## 📄 许可证

[MIT License](./LICENSE)

## 🙏 致谢

- [Formily](https://github.com/alibaba/formily) - 强大的表单解决方案
- [Ant Design](https://github.com/ant-design/ant-design) - 优秀的 React UI 库
- [React](https://github.com/facebook/react) - 用于构建用户界面的 JavaScript 库

<div align="center">
  <sub>Built with ❤️ by <a href="https://github.com/kway-teow">KwayTeow</a></sub>
</div>