@wordrhyme/auto-crud
v1.23.2
Published
Schema-first CRUD components with auto-generated tables and forms
Readme
@wordrhyme/auto-crud
Schema-first CRUD components with auto-generated tables and forms
基于 Zod Schema 自动生成完整 CRUD 界面的低代码 React 组件库。
✨ 特性
- 🚀 零配置 CRUD: 从 Zod Schema 自动生成表格和表单
- 🎨 高级数据表格: 基于 TanStack Table,支持排序、过滤、分页
- 📝 智能表单: 集成 Formily,支持复杂表单联动
- 🔌 灵活集成: 支持 tRPC、REST API 或内存数据源
- 🎯 类型安全: 完整的 TypeScript 类型推断
- 🌐 URL 状态同步: 使用 nuqs 实现 URL 状态管理
- 🎭 三种过滤模式: Simple / Advanced / Command
- 🔄 批量操作: 支持批量更新和删除
📦 安装
# pnpm
pnpm add @wordrhyme/auto-crud zod sonner
# npm
npm install @wordrhyme/auto-crud zod sonner
# yarn
yarn add @wordrhyme/auto-crud zod sonnerPeer Dependencies
{
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0",
"sonner": "^2.0.0",
"zod": "^3.0.0 || ^4.0.0"
}🚀 快速开始
基础示例
import { AutoCrudTable, useAutoCrudResource, createMemoryDataSource } from "@wordrhyme/auto-crud";
import { z } from "zod";
// 1. 定义 Zod Schema
const taskSchema = z.object({
id: z.string(),
title: z.string(),
status: z.enum(["todo", "in-progress", "done"]),
priority: z.enum(["low", "medium", "high"]),
createdAt: z.date(),
});
type Task = z.infer<typeof taskSchema>;
// 2. 创建数据源
const dataSource = createMemoryDataSource<Task>({
data: [
{ id: "1", title: "Task 1", status: "todo", priority: "high", createdAt: new Date() },
{ id: "2", title: "Task 2", status: "done", priority: "low", createdAt: new Date() },
],
onCreate: async (data) => { /* 创建逻辑 */ },
onUpdate: async (id, data) => { /* 更新逻辑 */ },
onDelete: async (id) => { /* 删除逻辑 */ },
});
// 3. 使用组件
function TasksPage() {
const resource = useAutoCrudResource({
dataSource,
schema: taskSchema,
});
return (
<AutoCrudTable
title="任务管理"
schema={taskSchema}
resource={resource}
/>
);
}与 tRPC 集成
import { AutoCrudTable, useAutoCrudResource, createTRPCDataSource } from "@wordrhyme/auto-crud";
import { trpc } from "@/lib/trpc/client";
import { createSelectSchema } from "drizzle-zod";
import { tasks } from "@/db/schema";
const taskSchema = createSelectSchema(tasks);
function TasksPage() {
// URL 状态管理
const [queryParams] = useQueryStates({
page: parseAsInteger.withDefault(1),
perPage: parseAsInteger.withDefault(10),
sort: getSortingStateParser().withDefault([]),
filters: getFiltersStateParser().withDefault([]),
});
// 创建 tRPC 数据源
const dataSource = createTRPCDataSource({
router: trpc.tasks,
queryInput: queryParams,
});
const resource = useAutoCrudResource({
dataSource,
schema: taskSchema,
});
return (
<AutoCrudTable
title="任务管理"
schema={taskSchema}
resource={resource}
fields={{
id: { hidden: true },
status: { label: "状态" },
priority: { label: "优先级" },
}}
table={{
filterModes: ["simple", "advanced", "command"],
batchFields: ["status", "priority"],
}}
/>
);
}📖 核心概念
Schema First 理念
Zod Schema → 自动推断字段类型 → 生成表格列 + 表单字段优势:
- ✅ 单一数据源(SSOT)
- ✅ 类型安全
- ✅ 零手动配置
- ✅ Schema 变更自动同步
数据源(Data Source)
@wordrhyme/auto-crud 支持三种数据源:
1. 内存数据源(Memory Data Source)
适合:原型开发、演示、测试
import { createMemoryDataSource } from '@wordrhyme/auto-crud';
const dataSource = createMemoryDataSource(initialData);
const result = await dataSource.list({
page: 1,
perPage: 10,
filters: [{ id: 'status', operator: 'inArray', value: ['draft', 'published'] }],
sort: [
{ id: 'createdAt', desc: true },
{ id: 'id', desc: false },
],
});筛选支持省略 operator / eq(严格相等)和 inArray(字段值属于给定数组);其他 operator 会报错。排序按配置顺序比较,前一字段相同时使用下一字段,再进行分页。内存数据源不执行全文搜索。
2. tRPC 数据源(tRPC Data Source)
适合:全栈 TypeScript 项目
import { createTRPCDataSource } from '@wordrhyme/auto-crud';
const dataSource = createTRPCDataSource({
router: trpc.tasks,
queryInput: { page: 1, perPage: 10 },
});要求:后端需要使用 @wordrhyme/auto-crud-server 创建 CRUD 路由。
3. 自定义数据源(Custom Data Source)
适合:REST API、GraphQL 等
const dataSource: DataSource<Task> = {
list: async (params) => {
const response = await fetch(`/api/tasks?${new URLSearchParams(params)}`);
return response.json();
},
get: async (id) => {
const response = await fetch(`/api/tasks/${id}`);
return response.json();
},
create: async (data) => {
const response = await fetch('/api/tasks', {
method: 'POST',
body: JSON.stringify(data),
});
return response.json();
},
update: async (id, data) => {
const response = await fetch(`/api/tasks/${id}`, {
method: 'PATCH',
body: JSON.stringify(data),
});
return response.json();
},
delete: async (id) => {
await fetch(`/api/tasks/${id}`, { method: 'DELETE' });
},
deleteMany: async (ids) => {
await fetch('/api/tasks/batch', {
method: 'DELETE',
body: JSON.stringify({ ids }),
});
},
};🎨 组件 API
<AutoCrudTable />
完整的 CRUD 表格组件。
Props
interface AutoCrudTableProps<TSchema> {
// 必需
schema: TSchema; // Zod Schema
resource: UseAutoCrudResourceReturn<TSchema>; // useAutoCrudResource 返回值
// 可选
title?: string;
description?: string;
fields?: Fields; // 统一字段配置
table?: {
hidden?: string[]; // 隐藏的列
overrides?: Record<string, any>; // 列覆盖配置
getRowId?: (record: z.output<TSchema>) => string; // 稳定行标识;展开时必填
expandedRow?: (
record: z.output<TSchema>,
row: Row<z.output<TSchema>>,
) => React.ReactNode; // 展开行内容,row 提供已解析的单元格上下文
rowFooter?: (
record: z.output<TSchema>,
row: Row<z.output<TSchema>>,
) => React.ReactNode; // 跨全部可见列的行尾内容,与展开状态无关
filterModes?: FilterMode | FilterMode[]; // 过滤模式
batchFields?: (string | BatchUpdateField)[]; // 批量更新字段
/** @deprecated 新代码请使用 actions.batch */
batchActions?: BatchActionConfig<z.output<TSchema>>;
defaultSort?: any[]; // 手动 resource 的 UI 默认排序;useAutoCrudResource 请配置 options.defaultSort
};
form?: {
overrides?: Record<string, any>; // 表单覆盖配置
columns?: number; // 表单列数
labelAlign?: 'left' | 'top' | 'right'; // 默认 top;left/right 为左右布局及标签文字对齐
labelWidth?: number | string; // 左右布局的标签宽度,数字单位为 px
};
/**
* 行操作配置,或统一配置 toolbar/row/batch。
*
* 旧写法 actions={[...]} 仍表示行操作;
* 新写法 actions={{ toolbar, row, batch }} 可集中配置三类操作。
*/
actions?:
| RowActionConfig<z.output<TSchema>>
| {
toolbar?: ToolbarActionConfig;
row?: RowActionConfig<z.output<TSchema>>;
batch?: BatchActionConfig<z.output<TSchema>>;
};
/** @deprecated 新代码请使用 actions.toolbar */
toolbar?: ToolbarActionConfig;
/** @deprecated 新代码请使用 actions.toolbar */
toolbarActions?: ToolbarActionConfig;
}展开行详情
配置 table.expandedRow 后,表格自动添加展开箭头。默认全部收起,允许同时展开多行。设置 table.defaultExpanded: true 可在首次展示时展开全部行;刷新保留用户的展开选择。该选项仅用于初始化,不控制当前展开状态。
必须提供 TanStack Table 的 getRowId,使用稳定且唯一的业务主键,避免分页、排序后展开错位。
展开内容可使用 cqw 单位,以表格可视区域的宽度为基准,避免宽表中的详情被横向裁切。
<AutoCrudTable
schema={orderSchema}
resource={resource}
table={{
getRowId: (order) => order.id,
expandedRow: (order) => <OrderDetails orderId={order.id} />,
}}
/>回调接收当前行的原始记录,并同步返回 React 内容。详情组件只在展开时挂载,收起时卸载; 可由详情组件按订单 ID 查询数据并处理加载、错误和重试,也可直接使用记录中已有的明细。 明细数据及其字段权限由业务组件和现有服务负责。
详情区域跨全部可见列,不计入分页条数,也不参与主表选择或导出。
未启用 defaultExpanded 时,数据更新后的展开状态遵循 TanStack Table 默认重置行为。
AutoTable 同样支持 getRowId 和 expandedRow;直接使用 DataTable 时,需自行配置 TanStack 展开能力及触发按钮。
expandedRow 的第二个参数是当前 TanStack Row,可通过 row.getAllCells() 读取已解析的列和单元格上下文,复用字段渲染器及数据源标签。只接收订单数据的单参数回调仍可使用。
行尾内容
table.rowFooter(record, row) 在每行主内容下方、展开详情上方渲染跨全部可见列的内容,收起时仍显示;它不要求配置 getRowId 或启用展开。
每次渲染对当前行调用一次,返回 null、undefined 或 false 时不创建额外表格行。其他返回值(包括 0)按 React 内容渲染。
行尾沿用 classNames.tr 和 classNames.td,消费侧可通过内容类名配合 classNames.td 的 :has() 选择器单独调整内边距。
AutoTable 和 DataTable 通过直接传入 rowFooter 使用同一契约;未配置时保留原有 DOM。
表格状态与 URL 参数
同页显示多个表格时,在资源 Hook 中配置独立的分页、排序和条件连接符参数名,AutoCrudTable 会自动传给表格:
const resource = useAutoCrudResource({
router: trpc.orders,
schema: orderSchema,
queryKeys: {
page: 'ordersPage',
perPage: 'ordersSize',
sort: 'ordersSort',
joinOperator: 'ordersJoin',
},
});
<AutoCrudTable
id="orders"
schema={orderSchema}
resource={resource}
table={{
enableRowSelection: false,
initialColumnVisibility: { createdAt: false },
}}
/>;未配置的参数名保留默认值。搜索仍使用共享的 search 参数,字段筛选仍使用字段名;queryKeys 不隔离这些值。筛选或搜索变化时,仅重置该表格对应的页码。直接使用 AutoTable 时传入相同的 queryKeys;table.queryKeys 可覆盖资源提供的整组配置。
全局搜索输入立即显示,停止输入 200ms 后提交查询并回到第一页;清空立即提交,中文输入法组词期间不查询。可以通过 table.search: { debounceMs: 0 } 恢复即时查询,或指定其他延时;直接使用 AutoTable 时配置 search.debounceMs。浏览器导航或其他 URL 状态变化会取消尚未提交的搜索,并按 URL 恢复输入框。
enableRowSelection 默认 true,设为 false 后关闭行选择并隐藏选择列和批量操作栏。initialColumnVisibility 只设置首次显示的列,用户仍可通过列设置切换;它不同于 table.hidden 对列的排除。
useAutoCrudResource()
连接数据源到组件的 Hook。
参数
interface UseAutoCrudResourceConfig<TData> {
dataSource: DataSource<TData>; // 数据源
schema: z.ZodType<TData>; // Zod Schema
options?: {
defaultSort?: Array<{ id: string; desc: boolean }> | false;
// undefined: schema 有 createdAt 时默认 createdAt desc
// false: 不应用默认排序
};
}返回值
interface UseAutoCrudResourceReturn<TSchema, TData> {
// 主键字段名;未提供时 AutoCrudTable 默认按 "id" 读取
idKey?: keyof TData & string;
// 表格数据
tableData: {
data: TData[];
pageCount: number;
};
// 模态框状态
modal: {
variant: 'dialog' | 'sheet';
createOpen: boolean;
editOpen: boolean;
viewOpen: boolean;
deleteOpen: boolean;
selected: TData | null;
copySource: TData | null;
};
// 操作方法
handlers: {
openCreate: () => void;
openEdit: (item: TData) => void;
openView: (item: TData) => void;
openDelete: (item: TData) => void;
copyRow: (item: TData) => void;
closeModals: () => void;
submitCreate: (data: TData) => Promise<void>;
submitUpdate: (data: TData) => Promise<void>;
confirmDelete: () => Promise<void>;
deleteMany: (rows: TData[]) => Promise<void>;
updateMany: (rows: TData[], data: Record<string, unknown>) => Promise<void>;
};
// 加载状态
mutations: {
isCreating: boolean;
isUpdating: boolean;
isDeleting: boolean;
};
}🔧 字段配置
Field 类型
interface Field {
/** 字段标签(表格和表单共用) */
label?: string;
/** 默认表格/详情文本和 CSV 值格式化;undefined 使用原来的默认行为 */
format?: (
value: unknown,
context: { row: Record<string, unknown>; target: 'display' | 'export' },
) => string | undefined;
/** 是否隐藏(表格和表单都隐藏) */
hidden?: boolean;
/** 表格特定配置 */
table?: {
hidden?: boolean; // 仅表格隐藏
classNames?: { th?: string; td?: string }; // 该列的表头和正文类名
meta?: Record<string, unknown>; // 筛选器配置
[key: string]: unknown;
};
/** 表单特定配置 */
form?: {
'x-hidden'?: boolean; // 仅表单隐藏
'x-component'?: string; // 组件类型
'x-component-props'?: Record<string, unknown>; // 组件属性
'x-reactions'?: object; // 字段联动
[key: string]: unknown;
};
}
type Fields = Record<string, Field>;值格式化
在字段上配置 format,表格和详情使用 target: 'display',顶部工具栏的选中/筛选导出及内置批量导出使用 target: 'export'。value 是格式化前的值,row 是原始记录。
fields={{
discount: {
format: (value) => `${value}%`,
},
createdAt: {
label: t('fields.createdAt'),
format: (value, { target }) => {
if (target !== 'export') return undefined;
if (value === null || value === undefined) return '';
const date = value instanceof Date ? value : new Date(String(value));
return Number.isNaN(date.getTime()) ? '' : date.toISOString();
},
},
}}返回字符串(包括空字符串)时使用该结果;返回 undefined 时保留原有默认展示或原始 CSV 值。格式化只影响输出,不改变排序、筛选、表单或保存的数据。显式自定义 cell 仍负责自己的界面渲染;声明式 table.display / table.options / table.dataSource 按已有优先级接管单元格时也会应用 format。
导出保留已有的列、字段名表头和权限排除规则。翻译继续在现有 label、选项和 format 中使用应用的 t();无需另配导出列或语言。
列宽与单元格样式
fields.xxx.table 中的 size、minSize 和 maxSize 控制列宽。fields.xxx.table.classNames 按元素分组配置该列的 CSS 类名:th 应用于该列的表头单元格,td 应用于该列每一行的正文单元格。
任一可见列设置有限的 maxSize 后,表格使用固定列宽布局,其他列采用各自的 size 或 TanStack 默认宽度。默认正文保持单行,超出列宽的文本省略;通过 fields.xxx.table.classNames.td 可以为该列配置换行展示。
fields={{
primaryContactValue: {
table: {
size: 250,
minSize: 250,
maxSize: 250,
classNames: {
th: 'text-center',
td: 'whitespace-normal break-words',
},
},
},
}}全局表格类名
组件顶层的 table.classNames 为整个表格设置类名,所有值均为 CSS 类名字符串。
| 配置 | 作用范围 |
| ------- | -------------------------------- |
| table | <table> 元素 |
| thead | <thead> 表头区域 |
| tbody | <tbody> 正文区域 |
| tr | 所有表头行、正文行和空状态行 |
| th | 所有表头单元格 |
| td | 所有正文单元格,包括空状态单元格 |
单元格类名按默认类名、全局类名、列级类名的顺序合并;存在冲突的 Tailwind 类名由后者覆盖。空状态单元格跨越所有列,只应用全局 td 类名。
<AutoCrudTable
schema={schema}
resource={resource}
table={{
classNames: {
table: 'text-xs',
thead: 'bg-muted',
tbody: 'text-foreground',
tr: 'hover:bg-accent/50',
th: 'h-12 text-left',
td: 'py-3 text-left',
},
}}
fields={{
primaryContactValue: {
table: {
classNames: {
th: 'text-center',
td: 'text-center whitespace-normal break-words',
},
},
},
}}
/>直接使用 AutoTable 或 DataTable 时,通过组件的 classNames prop 传入同一组全局类名。直接定义 TanStack 列时,通过 columnDef.meta.classNames 配置该列的 th、td。
基础配置
<AutoCrudTable
schema={taskSchema}
resource={resource}
fields={{
id: { hidden: true }, // 表格和表单都隐藏
title: { label: "标题" }, // 自定义标签
createdAt: {
label: "创建时间",
form: { "x-hidden": true }, // 仅表单隐藏
},
}}
/>表格筛选器配置
<AutoCrudTable
schema={taskSchema}
resource={resource}
fields={{
status: {
label: "状态",
table: {
meta: {
variant: "select", // "text" | "select" | "multiSelect" | "date" | "dateRange" | "range"
options: [
{ label: "待处理", value: "pending" },
{ label: "已完成", value: "completed" },
],
},
},
},
amount: {
label: "金额",
table: {
meta: {
variant: "range",
range: [0, 10000],
unit: "¥",
},
},
},
}}
/>表单组件配置
<AutoCrudTable
schema={taskSchema}
resource={resource}
fields={{
description: {
label: "描述",
form: {
"x-component": "Textarea",
"x-component-props": { rows: 5 },
},
},
assignee: {
label: "负责人",
form: {
"x-component": "Combobox",
"x-component-props": { placeholder: "选择负责人" },
},
},
}}
/>字段联动
<AutoCrudTable
schema={taskSchema}
resource={resource}
fields={{
endDate: {
label: "结束日期",
form: {
"x-reactions": {
dependencies: ["startDate"],
when: "{{$deps[0] !== undefined}}",
fulfill: {
state: {
visible: true,
disabled: false,
},
},
},
},
},
}}
/>🎯 过滤模式
Simple 模式(默认)
- 适合:快速筛选常用字段
- 特点:下拉选择框,一键清除
- 示例:状态筛选、优先级筛选
table={{
filterModes: "simple",
}}Advanced 模式(高级筛选)
- 适合:复杂多条件查询
- 特点:Notion 风格,支持 AND/OR 逻辑
- 示例:
status = "done" AND priority = "high"
table={{
filterModes: "advanced",
}}Command 模式(命令面板)
- 适合:键盘流用户
- 特点:Linear 风格,快捷键
Cmd+K - 示例:快速搜索并添加筛选条件
table={{
filterModes: "command",
}}多模式切换
table={{
filterModes: ["simple", "advanced", "command"], // 第一个为默认模式
}}🔧 工具栏操作配置
排序与列设置的语言
AutoCrudTable 的 locale 同时控制刷新、排序和列设置。支持 zh-CN(默认)、en-US、ja-JP、ko-KR、fr-FR、de-DE、es-ES。排序与列设置的按钮提示、弹层、字段搜索、排序方向、空状态及排序拖动的无障碍说明和播报均随语言切换。
<AutoCrudTable schema={schema} resource={resource} locale="en-US" />
<AutoCrudTable
schema={schema}
resource={resource}
locale={{
tableControls: {
sort: { label: '排序规则' },
columns: { label: '显示列' },
},
}}
/>对象形式按现有规则与中文语言包深合并;未覆盖的词条保留中文。tableControls 在 AutoCrudLocale 中为可选字段,已有自定义语言包无需补全字段。
独立使用 AutoTable 或 DataTableViewOptions 时,排序和列设置保留原有英文默认值,可分别传入 resolveLocale('ja-JP').tableControls 或其 columns 词条组。业务字段和列名仍由调用方的 fields / 列配置提供。
toolbar 数组控制工具栏操作,设计思路完全对齐行操作 actions。旧 prop toolbarActions 仍兼容读取,但新代码请使用 toolbar。
内置操作类型:refresh(刷新)、create(新建)、import(导入)、export(导出)。
刷新固定显示在搜索筛选行右侧,顺序为 [排序] [刷新] [列设置];其 label、onClick、component 和隐藏配置仍由 toolbar 控制。其余操作保留在上方工具栏,没有可见操作时不占空行。
直接使用 AutoTable 时,可通过 toolbarExtra 插入排序与列设置之间的控件:
<AutoTable
schema={schema}
data={rows}
toolbarExtra={<Button onClick={refresh}>刷新</Button>}
/>只添加自定义按钮(内置保持默认)
只传 type: "custom" 项时,所有内置按钮(刷新、导入、导出、新建)保持原样,custom 项按 position 插入首部或尾部。
<AutoCrudTable
toolbar={[
{
type: 'custom',
component: <Button variant="outline">分类管理</Button>,
position: 'start',
},
{ type: 'custom', component: <Button variant="outline">批量标签</Button> }, // 默认 position: "end"
]}
/>
// 上方工具栏: 分类管理 · [导入] · [导出] · [新建] · 批量标签
// 搜索筛选行右侧: [排序] · [刷新] · [列设置]调整内置按钮顺序
数组中只要包含任意内置 type,就会完全接管工具栏 —— 未列出的内置按钮直接隐藏。刷新保持在搜索筛选行,其他按钮的渲染顺序严格按数组。
<AutoCrudTable
toolbar={[
{ type: 'create' }, // 新建移到最前
{ type: 'export', label: '导出 CSV' }, // 覆盖文案
// import 未列出 → 隐藏
]}
/>
// 渲染顺序: 新建 · 导出 CSV(导入按钮消失)覆盖内置按钮行为
<AutoCrudTable
toolbar={[
{ type: 'import' },
{ type: 'export' },
{
type: 'create',
label: '发布商品',
onClick: () => router.push('/products/new'), // 跳转详情页而非弹窗
},
]}
/>完全替换内置按钮组件
<AutoCrudTable
toolbar={[
{ type: 'export' },
{
type: 'create',
// 整个按钮替换
component: (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button>
<Plus className="mr-2 h-4 w-4" />
新建
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={() => create('simple')}>简易商品</DropdownMenuItem>
<DropdownMenuItem onClick={() => create('sku')}>多规格商品</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
},
]}
/>混合 custom 和内置
<AutoCrudTable
toolbar={[
{ type: 'custom', component: <CategoryFilter onChange={setCategory} /> },
{ type: 'export' },
{ type: 'create', label: '发布', onClick: () => router.push('/products/new') },
]}
/>
// 渲染顺序: 分类筛选 · 导出 · 发布(导入隐藏)与 permissions 的交互
toolbar 与 permissions 的交互规则如下:
permissions.can.create = false→ 即使配置了{ type: "create" },新建按钮仍不渲染permissions.can.export = false→ 即使配置了{ type: "export" },导出按钮仍不渲染- 内置项即使使用
component完全替换渲染,也仍然受对应权限控制 type: "custom"不受 permissions 影响,由业务方自行控制
<AutoCrudTable
permissions={{
can: { create: isAdmin, export: true, delete: isAdmin },
}}
toolbar={[
{ type: 'export' }, // ✅ 始终渲染
{ type: 'create', label: '发布商品' }, // 🔒 仅 isAdmin 时渲染
{
type: 'custom', // ✅ 不受 permissions 影响
component: isEditor ? <Button>审核</Button> : null, // 业务方自行守卫
},
]}
/>toolbar 传参高级语法(函数式)
如果你的目标是拦截并修改基于原顺序的所有内容,你还可以传递一个函数:
<AutoCrudTable
// defaults 即内置按钮的信息,在此数组里你可以随意 map、过滤或插值
toolbar={(defaults) =>
defaults.map((btn) =>
btn.type === 'create'
? { ...btn, label: '发布商品', onClick: () => router.push('/products/new') }
: btn,
)
}
/>
// 非常适合“只盖头不换面”的场景,不会导致内置按钮丢失或顺序打乱ToolbarActionItem 类型
type ActionMeta = {
id?: string; // 插件注册时用于区分同 type 的 action
order?: number; // 插件注册排序,默认 100
hidden?: boolean; // 显式隐藏该 action
};
type ToolbarActionItem = ToolbarBuiltinActionItem | ToolbarCustomActionItem;
type ToolbarActionConfig =
| ToolbarActionItem[]
| ((defaults: ToolbarBuiltinActionItem[]) => ToolbarActionItem[]);
type ToolbarBuiltinActionItem = ActionMeta & {
type: 'refresh' | 'create' | 'import' | 'export';
onClick?: () => void; // 覆盖默认行为
label?: string; // 覆盖默认文案
component?: React.ReactNode | ((context: AutoCrudToolbarContext) => React.ReactNode);
};
type ToolbarCustomActionItem = ActionMeta & {
type: 'custom';
component: React.ReactNode | ((context: AutoCrudToolbarContext) => React.ReactNode);
position?: ActionPosition; // start/end 仅无内置项时生效;也支持 { anchor, side }
};
interface AutoCrudToolbarContext {
crudId: string;
idKey: string;
rowIds: string[];
selectedRowIds: string[];
selectedCount: number;
refresh?: () => Promise<unknown>;
openImport?: () => void;
exportData?: () => Promise<void>;
openCreate?: () => void;
isRefreshing: boolean;
isExporting: boolean;
}AutoCrudToolbarContext 是工具栏自定义组件的正式 command contract。自定义按钮需要复用 AutoCrud 内置能力时,直接调用 context 中的命令,不要绕过内部状态重新实现。
例如业务侧希望把默认“新建”按钮替换成“手动创建”,可以替换 type: "create" 的组件并调用 openCreate:
<AutoCrudTable
toolbar={[
{
type: 'create',
component: ({ openCreate }) => (
<Button onClick={() => openCreate?.()}>手动创建</Button>
),
},
]}
/>这里“手动创建”只是业务按钮文案,不是新的 AutoCrud 流程;它仍然打开 AutoCrud 原生的新建弹窗。openCreate、openImport、exportData 会按对应权限和能力可选暴露,扩展方应使用 ?.() 或自行控制 disabled 状态。
工具栏扩展 Resolver
宿主应用可以通过 setToolbarResolver 为指定 CRUD 注入额外工具栏动作。resolver 是普通纯函数,不是 React Hook;不要在 resolver 内调用 useRouter、useMemo 等 React Hooks。
import { AutoCrudTable, setToolbarResolver } from '@wordrhyme/auto-crud';
import type { AutoCrudToolbarResolver } from '@wordrhyme/auto-crud';
const toolbarResolver: AutoCrudToolbarResolver = (targetId, ownerActions, context) => {
if (targetId !== 'com.wordrhyme.shop.products') return [...ownerActions];
return [
...ownerActions,
{
type: 'custom',
component: <Button disabled={context.selectedCount === 0}>批量发布</Button>,
},
];
};
setToolbarResolver(toolbarResolver);插件式操作注册
跨模块扩展推荐使用 crudActions.register。它按 targetId 和区域注入操作,不需要业务页把所有插件动作手动拼到 props 中。
import { crudActions } from '@wordrhyme/auto-crud';
crudActions.register({
targetId: 'com.wordrhyme.shop.products',
zone: 'toolbar', // 'toolbar' | 'row' | 'batch'
ownerId: 'com.wordrhyme.product-lab',
actions: [
{ type: 'export', hidden: true },
{ type: 'create', label: '发布商品', order: 80 },
{
type: 'custom',
id: 'bulk-publish',
position: 'end',
component: ({ selectedCount }) => (
<Button disabled={selectedCount === 0}>批量发布</Button>
),
},
],
});同一个 ownerId + targetId + zone 再次注册会替换该 owner 的旧动作;卸载插件或页面时可调用 crudActions.unregister(ownerId)。
插件的 actions 数组与页面配置一样,用数组表达操作的相对顺序。例如,在删除前插入同步操作:
crudActions.register({
targetId: 'com.wordrhyme.shop.products',
zone: 'row',
ownerId: 'com.wordrhyme.sync',
actions: [{ type: 'custom', label: '同步', onClick: sync }, { type: 'delete' }],
});插件仍是增量合并:未提及的宿主或其他插件操作保留,隐藏内置项必须显式使用 hidden: true。
有可见内置项的数组按声明顺序排列:从第一个列出的内置项所在位置开始,依次插入自定义项,只在顺序冲突时移动已存在的内置项。
未提及的操作之间保持相对顺序。内置项的已有 handler 等属性保留,只有显式声明的属性会覆盖它们。
只有自定义项(或列出的内置项全部被隐藏)时,沿用 position: 'start' | 'end',同一位置内仍按数组顺序排列。
多插件按各自数组中最小的 order(未设置为 100)、ownerId 依次合并;后处理的数组在顺序冲突时优先,但不会删除前面的插件操作。
order 不再重排同一插件数组内的显示顺序。内置属性覆盖仍沿用原有的 action order、ownerId、注册序优先级,最后一个配置生效。
使用 order 排列同一插件操作的旧调用方,应把数组调整为所需顺序。最终权限过滤只移除不可用的内置操作,不改变其余操作顺序或授予权限。
统一位置契约
AutoCrud action 和 WordRhyme PluginSlot 共用 ActionPosition:"start"、"end",或 { anchor, side: "before" | "after" }。类型、schema、位置匹配和锚点排序从不依赖 React 的 @wordrhyme/auto-crud/position 导出。
positionActions(ownerActions, fills) 合并拥有方按钮和扩展数组:start fills 放在数组前,end 或未指定位置的 fills 放在数组后,相对位置按基础按钮锚点插入。AutoCrud 和 PluginSlot 共用此解析器。原有 action 数组及 start/end 排列规则保持不变。指定锚点时,在原有合并、覆盖和隐藏之后定位,order 按升序排列同一锚点的 fills。AutoCrud 使用合并后基础 action 的 id 作为锚点;原生按钮未设置 id 时使用 type。合并后的动作列表不存在锚点时,不显示依赖它的扩展;最终权限过滤继续沿用已有行为。
crudActions.register({
targetId: 'com.wordrhyme.shop.products',
zone: 'toolbar',
ownerId: 'com.wordrhyme.sync',
actions: [
{
type: 'custom',
component: SyncButton,
position: { anchor: 'create', side: 'before' },
order: 30,
},
],
});🎬 行操作配置
actions 旧数组写法控制每行下拉菜单的操作项;统一写法可使用 actions.row。两种写法都支持覆盖内置操作、添加自定义操作、完全自定义顺序。
只添加自定义项(内置不变)
<AutoCrudTable
actions={{
row: [
{ type: 'custom', label: '分配', onClick: (row) => assign(row.id) },
{
type: 'custom',
label: '预览',
onClick: (row) => preview(row),
position: 'start',
},
],
}}
/>
// 渲染顺序: 预览 · 查看 · 编辑 · 复制 · 删除 · 分配覆盖内置行为或隐藏某项
数组中只要包含任意内置 type,数组就会完全接管 —— 未列出的内置项自动隐藏。
<AutoCrudTable
actions={{
row: [
{ type: 'view', onClick: (row) => router.push(`/tasks/${row.id}`) }, // 覆盖跳转
{ type: 'custom', label: '分配', onClick: (row) => assign(row.id) },
{ type: 'edit' }, // 默认行为
// copy / delete 未列出 → 隐藏
],
}}
/>完全自定义顺序
<AutoCrudTable
actions={[
{ type: 'edit' },
{ type: 'copy' },
{ type: 'custom', label: '归档', onClick: archive, separator: true },
{ type: 'delete', separator: true },
]}
/>支持函数配置模式
如果只需要在原来的基础上做细微拦截处理,传入一个函数更省事:
<AutoCrudTable
actions={(defaults) =>
defaults.map((action) =>
action.type === 'delete'
? { ...action, label: '下架', variant: 'default' }
: action,
)
}
/>RowActionItem 类型
type RowActionItem<T> = RowBuiltinActionItem<T> | RowCustomActionItem<T>;
type RowActionConfig<T> =
| RowActionItem<T>[]
| ((defaults: RowBuiltinActionItem<T>[]) => RowActionItem<T>[]);
type RowBuiltinActionItem<T> = ActionMeta & {
type: 'view' | 'edit' | 'copy' | 'delete';
onClick?: (row: T) => void; // 不传则使用默认行为
label?: string; // 不传则使用默认文案
separator?: boolean; // 此项前加分隔线
};
type RowCustomActionItem<T> = ActionMeta & {
type: 'custom';
label?: string;
onClick?: (row: T) => void;
component?:
| React.ReactNode
| ((context: AutoCrudRowActionContext<T>) => React.ReactNode);
position?: ActionPosition; // start/end 仅无内置项时生效;也支持 { anchor, side }
separator?: boolean;
variant?: 'default' | 'destructive';
};
interface AutoCrudRowActionContext<T> {
open: (options: AutoCrudRowOpenOptions<T>) => void;
crudId: string;
idKey: string;
row: T;
rowId?: string;
openView: (row: T) => void;
openEdit?: (row: T) => void;
copyRow?: (row: T) => void;
openDelete?: (row: T) => void;
}统一打开入口
行操作上下文提供 open(options),旧的 openView、openEdit、copyRow、
openDelete 保持兼容:
open({ type: 'view', row });
open({ type: 'edit', row });
open({ type: 'copy', row });
open({ type: 'delete', row });
open({
type: 'custom',
component: <TransferDialog customer={row} open={false} onOpenChange={() => {}} />,
});AutoCrudRowOpenOptions<T> 是判别联合:内置操作必须传 row,
custom 必须传 component。内置操作复用旧方法的处理器,不可用的操作不执行;
仍可通过旧的可选方法(如 openEdit)判断是否应显示对应菜单项。
自定义 component 由开发者实现弹窗或抽屉,并接收 open/onOpenChange 控制。
AutoCrudTable 只管理生命周期,不额外包裹内置弹窗,也不会把普通组件自动变成弹窗。
自定义行操作弹窗
在行操作配置的 component 中使用 open 打开自定义弹窗:
{
type: 'custom',
component: ({ row, MenuItem, open }) => (
<MenuItem onSelect={() => open({
type: 'custom',
component: <TransferDialog customer={row} open={false} onOpenChange={() => {}} />,
})}>
交接
</MenuItem>
),
}TransferDialog 由开发者实现并接收 RowActionDialogProps。AutoCrudTable 托管
open、onOpenChange 和可选的 onDismiss(调用方传入的同名属性会被覆盖),
但不额外包裹弹窗。调用 onOpenChange(false) 或 onDismiss() 会卸载弹窗并清理状态;
每次 open({ type: 'custom', component }) 都创建新会话并替换当前自定义弹窗。
弹窗位于表格层,菜单关闭、列配置重建、翻页或筛选移除原行都不会卸载它。 它继续使用打开时传入的记录,关闭后再次打开才获取新的记录。 表格卸载时弹窗一起释放。弹窗自身负责 Portal、布局和业务提交。
🔄 批量操作
批量更新
<AutoCrudTable
schema={taskSchema}
resource={resource}
table={{
batchFields: ["status", "priority"],
}}
/>功能:
- 选择多行
- 点击批量更新按钮
- 选择字段和新值
- 一键更新所有选中行
批量悬浮栏操作顺序
actions.batch 控制多选后悬浮操作栏,设计思路对齐 actions.row 和 actions.toolbar。旧的 table.batchActions 仍兼容,但新代码建议使用 actions.batch。
内置操作类型:batchUpdate(批量更新字段下拉)、export(导出选中行)、delete(删除选中行)。
只传 type: "custom" 项时,默认批量操作保持原样;包含任意内置 type 时,将完全接管顺序,未列出的内置操作不渲染。
AutoCrudTable 默认不在悬浮栏重复显示导出按钮;需要悬浮栏导出时,在 actions.batch 中显式列出 { type: 'export' }。
<AutoCrudTable
schema={taskSchema}
resource={resource}
table={{
batchFields: ['status', 'priority'],
}}
actions={{
batch: [
{ type: 'batchUpdate' },
{
type: 'custom',
label: '同步选中项',
onClick: (rows) => syncSelected(rows),
},
{ type: 'export' },
{ type: 'delete' },
],
}}
/>也可以用函数式写法基于默认顺序插入业务操作:
<AutoCrudTable
actions={{
batch: (defaults) => [
defaults[0], // batchUpdate
{
type: 'custom',
component: ({ rows }) => <Button size="sm">同步 {rows.length} 项</Button>,
},
defaults[2], // delete
],
}}
/>批量删除
// 自动启用,无需配置
<AutoCrudTable schema={taskSchema} resource={resource} />功能:
- 选择多行
- 点击批量删除按钮
- 确认删除
- 一次性删除所有选中行
🔌 与其他库集成
与 Drizzle ORM 集成
import { createSelectSchema } from "drizzle-zod";
import { tasks } from "@/db/schema";
const taskSchema = createSelectSchema(tasks);
<AutoCrudTable schema={taskSchema} resource={resource} />与 Next.js 集成
// app/tasks/page.tsx
"use client";
import { AutoCrudTable } from "@wordrhyme/auto-crud";
export default function TasksPage() {
return <AutoCrudTable schema={taskSchema} resource={resource} />;
}🧰 工具函数
配置日期展示策略
通过 setDateFormatter 可以让 AutoCrud 内部日期跟随宿主的语言和时区策略:
import { setDateFormatter } from '@wordrhyme/auto-crud';
const disposeDateFormatter = setDateFormatter((date, options) =>
new Intl.DateTimeFormat(getCurrentLocale(), {
...options,
timeZone: getCurrentTimeZone(),
}).format(date),
);
// 应用卸载时移除当前注册
disposeDateFormatter();
// 传入 undefined 可清空全部注册
setDateFormatter(undefined);setDateFormatter 是进程/运行时级配置,建议在应用启动时注册一个稳定的 formatter。多个注册可以重叠,清理函数只移除对应注册,允许乱序清理。SSR 场景不要在每个请求中重复调用 setter;如需按请求选择语言或时区,应由稳定 formatter 通过宿主提供的并发安全上下文读取当前请求策略。
原有 setDateFormatter(formatter) 调用保持兼容:筛选器的已选日期标签继续使用宿主 formatter,包括其自定义格式和时区行为。
日期筛选日历可通过 setDateFormatter(formatter, { locale, timeZone }) 接收宿主配置(DateLocaleOptions)。语言或时区改变时重新注册并清理旧注册,已挂载的筛选器会同步更新月份、星期和日期标签。筛选值使用 YYYY-MM-DD 日历日字符串;服务端配置 resolveDateRange 时按宿主查询时区解析边界,否则使用服务端本地时区,并继续兼容时间戳输入。显式传入日历配置后,日期标签使用指定 locale,直接格式化日历日,不再调用 formatter 或进行时间点的时区转换。timeZone 仅随注册保存宿主策略,不会改变日历的“今天”、默认月份或自动配置服务端查询时区;业务时区边界仍须由服务端 resolveDateRange 提供。
升级时请同时更新 @wordrhyme/auto-crud 与 @wordrhyme/auto-crud-server:新日历提交 YYYY-MM-DD,旧服务端默认解析器无法识别。自定义 resolveDateRange 也应接受此格式;已有时间戳 URL 仍可读取。
Schema Bridge - 核心转换函数
import {
parseZodField, // 解析 Zod 字段类型
createTableSchema, // Zod Schema → TanStack Table 列定义
createSelectColumn, // 创建选择列
createActionsColumn, // 创建操作列
createFormSchema, // Zod Schema → Formily Schema
createEditFormSchema, // 创建编辑表单 Schema(排除平台托管字段)
} from '@wordrhyme/auto-crud';自定义列渲染
使用 createTableSchema 的 overrides 参数自定义列渲染:
import { createTableSchema } from "@wordrhyme/auto-crud";
import { Badge } from "@shadcn/ui";
const columns = createTableSchema(taskSchema, {
overrides: {
status: {
label: "状态",
// 自定义 cell 渲染
cell: ({ row }) => {
const status = row.getValue("status");
return (
<Badge variant={status === "done" ? "success" : "secondary"}>
{status}
</Badge>
);
},
},
priority: {
label: "优先级",
// 自定义列配置
size: 100,
enableSorting: false,
},
},
exclude: ["id", "createdAt"], // 排除字段
});自定义表单渲染
使用 createFormSchema 的 overrides 参数自定义表单组件:
import { createFormSchema } from '@wordrhyme/auto-crud';
const formSchema = createFormSchema(taskSchema, {
overrides: {
description: {
'x-component': 'Textarea',
'x-component-props': { rows: 5 },
},
status: {
'x-component': 'Select',
'x-component-props': {
options: [
{ label: '待办', value: 'todo' },
{ label: '完成', value: 'done' },
],
},
},
dueDate: {
'x-component': 'DatePicker',
'x-component-props': { format: 'YYYY-MM-DD' },
},
},
layout: 'grid',
gridColumns: 2,
exclude: ['id', 'createdAt'],
});🔀 三种 Schema 类型
@wordrhyme/auto-crud 支持三种 Schema 输入格式,通过 SchemaAdapter 统一处理:
1. Zod Schema(推荐)
import { z } from 'zod';
const taskSchema = z.object({
id: z.string(),
title: z.string(),
status: z.enum(['todo', 'in-progress', 'done']),
priority: z.enum(['low', 'medium', 'high']),
createdAt: z.date(),
});2. JSON Schema
import type { JSONSchema } from '@wordrhyme/auto-crud';
const taskSchema: JSONSchema = {
type: 'object',
properties: {
id: { type: 'string' },
title: { type: 'string', title: '标题' },
status: {
type: 'string',
enum: ['todo', 'in-progress', 'done'],
title: '状态',
},
createdAt: { type: 'string', format: 'date-time' },
},
required: ['id', 'title'],
};3. 简化配置(Simple Config)
import type { SimpleFieldsConfig } from '@wordrhyme/auto-crud';
const taskSchema: SimpleFieldsConfig = {
id: { type: 'string', required: true },
title: { type: 'string', label: '标题', required: true },
status: {
type: 'select',
label: '状态',
options: ['todo', 'in-progress', 'done'],
},
description: { type: 'textarea', label: '描述' },
createdAt: { type: 'datetime' },
};SchemaAdapter 使用
import { SchemaAdapter } from '@wordrhyme/auto-crud';
// 自动检测 Schema 类型
const type = SchemaAdapter.detectType(schema); // "zod" | "json" | "simple"
// 转换为统一的字段定义
const fields = SchemaAdapter.toUnified(schema);
// 转换为 Formily Schema
const formilySchema = SchemaAdapter.toFormily(fields);🧩 基础组件(自定义组合)
如果 AutoCrudTable 不能满足需求,可以使用基础组件自行组合:
组件层级
AutoCrudTable ← 高级封装,一站式 CRUD
├── AutoTable ← 表格 + 工具栏 + 筛选器
│ ├── DataTable ← 纯表格组件(TanStack Table)
│ ├── AutoTableActionBar ← 批量操作栏
│ └── AutoTableSimpleFilters ← 简单筛选器
├── AutoForm ← 表单组件(Formily)
└── CrudFormModal ← 表单弹窗(创建/编辑/查看)使用 DataTable 组件
import { DataTable, createTableSchema, createSelectColumn, createActionsColumn } from "@wordrhyme/auto-crud";
function CustomTable({ data }) {
const columns = [
createSelectColumn(),
...createTableSchema(taskSchema, { exclude: ["id"] }),
createActionsColumn([
{ label: "查看", onClick: (row) => console.log("View", row) },
{ label: "编辑", onClick: (row) => console.log("Edit", row) },
{ label: "复制", onClick: (row) => console.log("Copy", row) },
{ label: "删除", onClick: (row) => console.log("Delete", row), separator: true, variant: "destructive" },
]),
];
return (
<DataTable
columns={columns}
data={data}
pageCount={10}
/>
);
}使用 AutoForm 组件
import { AutoForm } from "@wordrhyme/auto-crud";
function CustomForm() {
return (
<AutoForm
schema={taskSchema}
gridColumns={2}
onSubmit={(values) => console.log(values)}
/>
);
}详情使用同一条 Formily 渲染链路,通过 mode="view" 启用 readPretty,无需传入 onSubmit,也不会显示提交按钮:
<AutoForm
mode="view"
schema={taskSchema}
initialValues={selectedTask}
fields={fields}
gridColumns={2}
/>创建、编辑排除 ID 和审计托管字段;详情保留 ID、创建时间和更新时间。form: false 和字段级 form['x-hidden'] 只影响创建、编辑;全局 hidden 和 permissions.deny 仍限制详情字段。其他表单覆盖配置、布局、scope 和选项标签继续共用。
内置字段提供阅读态映射;通过 components.register() 注册的自定义组件应使用 Formily mapReadPretty 实现自己的阅读态。AutoCrudTable 详情仍展示当前选中记录,不会额外请求单条接口。
详情默认单列,列数由 AutoCrudTable 的 form.columns 或 AutoForm 的 gridColumns 控制,使用浅色标签和宽松间距;长文本、数组和对象默认占满整行,字段 gridSpan 可指定跨度。单选标签显示为文字,多选标签使用轻量徽标。长内容自动换行;弹窗最高为视口高度的 85%,超出后正文滚动,标题保持可见。
AutoCrudTable 的 form.labelAlign 和 form.labelWidth 同时作用于创建、编辑及详情弹窗。例如 form={{ columns: 1, labelAlign: 'left', labelWidth: 100 }} 表示单列、左侧标签文字左对齐,标签宽度为 100px。top 表示上下布局(默认),right 表示左侧标签文字右对齐;labelWidth 仅在 left / right 布局时生效。
使用 useDataTable Hook
import { useDataTable, DataTable, DataTablePagination } from "@wordrhyme/auto-crud";
function CustomDataTable({ data, pageCount }) {
const { table } = useDataTable({
data,
columns,
pageCount,
initialState: {
pagination: { pageIndex: 0, pageSize: 10 },
sorting: [{ id: "createdAt", desc: true }],
},
});
return (
<div>
<DataTable table={table} />
<DataTablePagination table={table} />
</div>
);
}组件组合示例
import {
AutoTable,
AutoForm,
CrudFormModal,
useAutoCrudResource,
createTableSchema,
createFormSchema,
} from "@wordrhyme/auto-crud";
function CustomCrudPage() {
const resource = useAutoCrudResource({ dataSource, schema: taskSchema });
const columns = createTableSchema(taskSchema, {
overrides: {
status: {
cell: ({ row }) => <StatusBadge status={row.getValue("status")} />,
},
},
});
const formSchema = createFormSchema(taskSchema, {
exclude: [
"id",
"createdAt",
"updatedAt",
"createdBy",
"createdByType",
"updatedBy",
"updatedByType",
],
});
return (
<div>
{/* 自定义表格 */}
<AutoTable
columns={columns}
data={resource.tableData.data}
pageCount={resource.tableData.pageCount}
filterMode="simple"
/>
{/* 自定义表单弹窗 */}
<CrudFormModal
mode={resource.modal.editOpen ? "edit" : "create"}
open={resource.modal.createOpen || resource.modal.editOpen}
onClose={resource.handlers.closeModals}
schema={formSchema}
initialValues={resource.modal.selected}
onSubmit={resource.modal.editOpen
? resource.handlers.submitUpdate
: resource.handlers.submitCreate}
/>
</div>
);
}📦 导出的类型
// Auto-CRUD 组件
export { AutoCrudTable } from './components/auto-crud/auto-crud-table';
export type {
Field,
Fields,
AutoCrudTableProps,
} from './components/auto-crud/auto-crud-table';
export { AutoForm } from './components/auto-crud/auto-form';
export { AutoTable } from './components/auto-crud/auto-table';
export { AutoTableActionBar } from './components/auto-crud/auto-table-action-bar';
export { AutoTableSimpleFilters } from './components/auto-crud/auto-table-simple-filters';
export { CrudFormModal } from './components/auto-crud/crud-form-modal';
// 数据表格组件
export { DataTable } from './components/data-table/data-table';
export { DataTableAdvancedToolbar } from './components/data-table/data-table-advanced-toolbar';
export { DataTableColumnHeader } from './components/data-table/data-table-column-header';
export { DataTableFacetedFilter } from './components/data-table/data-table-faceted-filter';
export { DataTablePagination } from './components/data-table/data-table-pagination';
export { DataTableToolbar } from './components/data-table/data-table-toolbar';
export { DataTableViewOptions } from './components/data-table/data-table-view-options';
// Hooks
export { useAutoCrudResource, noopToastAdapter } from './hooks/use-auto-crud-resource';
export type {
ToastAdapter,
CrudHooks,
UseAutoCrudResourceOptions,
} from './hooks/use-auto-crud-resource';
export { useDataTable } from './hooks/use-data-table';
export { useReadableFilters } from './hooks/use-readable-filters';
export { useUrlState, useQueryState, useQueryStates } from './hooks/use-url-state';
// Schema Bridge - 核心工具
export {
parseZodField,
createTableSchema,
createSelectColumn,
createActionsColumn,
} from './lib/schema-bridge/zod-to-columns';
export {
createFormSchema,
createEditFormSchema,
} from './lib/schema-bridge/zod-to-formily';
export { SchemaAdapter } from './lib/schema-bridge/schema-adapter';
export type {
ColumnOverrides,
FormSchemaOverrides,
CreateTableSchemaOptions,
CreateFormSchemaOptions,
UnifiedSchema,
JSONSchema,
SimpleFieldsConfig,
UnifiedField,
} from './lib/schema-bridge';
// 数据源
export { createTRPCDataSource, createMemoryDataSource } from './lib/data-source';
export type { DataSource, ListParams, ListResult } from './lib/data-source';
// 工具函数
export { cn } from './lib/utils';
export { formatDate, setDateFormatter } from './lib/format';
export type { DateFormatter } from './lib/format';
export { humanize } from './lib/humanize';🤝 贡献
欢迎贡献代码!请查看 CONTRIBUTING.md。
📄 许可证
MIT © wordrhyme
🔗 相关链接
💡 灵感来源
- TanStack Table - 强大的表格库
- Formily - 灵活的表单解决方案
- Shadcn UI - 优雅的 UI 组件
- Notion - 高级筛选器设计
- Linear - 命令面板设计
Status badge colors
For table.display: "badge", a scalar field's table.options entries may set badgeTone to neutral, success, warning, or info. This renders a tinted, outlined rounded label with a decorative dot. Labels remain readable without color; omitted tones retain the default badge. display: "text" is unaffected. Domain-specific state-to-tone mappings belong in the consuming plugin metadata.
Registered custom actions may set before: "delete" (or another builtin action type) to appear immediately before that action. If the builtin is absent, the existing position fallback applies. This only controls ordering and does not add or grant the target action.
Custom row components receive MenuItem in their action context. Use this supplied primitive instead of importing a menu item from another UI bundle: the menu root and item must share the same Radix runtime context. Prevent the select event's default dismissal when the component owns an open dialog, so the menu does not unmount the workflow.
Detail presentation
Details automatically share field labels, enum/dataSource mappings and
fields[field].table presentation settings (label, display, options,
dataSource) with the list. No presentation switch is required. Default details
show full text and all array items, preserving localized boolean labels.
Table-only hidden fields remain available in details; shared hidden and
permissions.deny always take precedence. Labels are resolved from the selected
record, including when it is absent from the current list page.
Details share the form's column count, field spans and x-index order (including
form.overrides). Fields without an index retain schema order. List column order
does not control detail layout, even with view.presentation: 'table'.
view.overrides[field].index takes precedence for detail-only ordering. Fields
hidden only in forms remain available in details; use detail ordering to place
read-only business fields next to related information or audit fields at the end.
Field spans come from the shared form configuration; details do not expand arrays,
objects or long-text fields to a full row automatically.
<AutoCrudTable
schema={schema}
resource={resource}
fields={{ description: { table: { hidden: true } } }}
view={{
overrides: {
description: { label: 'Full description', index: 0 },
region: { cell: ({ getValue }) => <strong>{String(getValue())}</strong> },
},
}}
/>view.overrides changes details only. Custom list cell callbacks are not inherited
by default because they can contain list actions or depend on table state. To
explicitly reuse them, set view.presentation: 'table'; detail overrides still win.
This provides a real separate single-row TanStack context, not the original
list's pagination, selection or row index. Reused custom cells retain their own
truncation and interaction behavior.
When fields[field].table.component declares a component and the caller resolves it
into a table.overrides[field].cell, that cell is preserved alongside display,
options and dataSource. Without a resolved cell, default presentation still
applies. Fields without table.component keep their existing presentation priority.
状态徽标颜色
对于 table.display: "badge",标量字段的 table.options 可设置 badgeTone,支持 neutral、success、warning、info。徽标保留文字标签并附带装饰圆点,未配置颜色时沿用原有徽标样式,纯文本展示不受影响。业务状态与颜色的对应关系由调用方配置。
自定义行操作的菜单上下文
行操作组件接收上下文中的 MenuItem,应使用它以保证菜单根节点和菜单项共享同一运行时上下文。组件需要在菜单中保持弹窗会话时,可在选择事件中调用 preventDefault(),避免菜单关闭导致组件卸载。
Row action menu UI contract
The row action menu created by createActionsColumn uses the public
@wordrhyme/ui entry (a peer dependency). Custom component actions, including
WordRhyme Host resource permission actions, must use menu items from that same
shared entry. A private Radix or @wordrhyme/shadcn menu item cannot be inserted
into this menu.
The package build keeps @wordrhyme/ui external. In a WordRhyme plugin remote,
consume the Host's existing Federation share using
'@wordrhyme/ui': { singleton: true, import: false }. Do not alias this import to
private source or substitute an unshared subpath. Independently implemented
menus remain supported when their context-dependent components stay together.
Runtime consumers must provide @wordrhyme/ui >=0.1.0-alpha.20 <0.2.0, which
adds the CommonJS export condition while keeping the same ESM module instance.
Publish that UI version before this AutoCrud change. The development dependency
is pinned to the already-published alpha.19 for reproducible ESM tests and type
checks until alpha.20 is published; it is not the supported CommonJS runtime.
The CommonJS export/identity regression belongs to the UI provider repository.
Filter-only fields
Use table: false with an explicit filter to keep a field in the standard
filter bar without rendering a data column. Shared hidden, permission deny,
and explicit table exclusions still hide the filter. Pass the same filter
configuration to the resource so URL values use the same variants/operators:
const fields = {
customerId: {
label: 'Customer',
table: false as const,
form: false as const,
filter: { variant: 'select' as const, dataSource: 'customers', index: 20 },
},
};
const resource = useAutoCrudResource({ router, schema, fields });
return <AutoCrudTable schema={schema} resource={resource} fields={fields} />;The field must exist in the schema or resource metadata, and the server must resolve its filter. A data source loads options; it does not translate query conditions. Standard filters share URL state, Reset, and pagination. Dynamically registered schema fields hydrate existing URL values without resetting the page.
按 ID 隐藏或替换自定义操作
拥有方为 custom 操作声明稳定 id 后,扩展可以在相同 CRUD target 和操作区域
(row、toolbar 或 batch)使用同 ID 替换该操作;拥有方的原位置保留。
替换使用扩展提供的完整操作,不继承原操作的组件或回调。
crudActions.register({
targetId: 'products',
zone: 'row',
ownerId: 'consumer',
actions: [{ type: 'custom', id: 'products.inspect', hidden: true }],
});hidden: true屏蔽同 target、同区域内所有匹配 ID 的 custom 操作,优先于替换。- 多个扩展提供同 ID 时,按已有
order、ownerId、注册序号排序,最后一个生效。 - 未匹配拥有方的 ID 只追加一次;不带 ID 的 custom 操作继续独立追加。
- 注销扩展后恢复拥有方操作;内置操作继续按
type合并及执行权限检查。 - custom 操作仍由业务方提供权限守卫;ID 不授予权限,也不影响后端鉴权。
Styles
Choose one mode and import only the highest-level package you use.
With Tailwind CSS v4, in your application stylesheet:
@import 'tailwindcss';
@import '@wordrhyme/auto-crud/tailwind.css';Without Tailwind CSS, in your application entry:
import '@wordrhyme/auto-crud/styles.css';See the shared style guide for theme setup, dark mode, and custom classes.
Optional pagination controls
Existing pagination defaults are preserved. Set table.pagination on AutoCrudTable
(or pagination on AutoTable / DataTable) to opt in. Applications can also
register options for a public CRUD id without changing the owning page:
import { tablePagination } from '@wordrhyme/auto-crud';
tablePagination.register('example.stores', {
alwaysShowFirstLast: true,
showPageJump: true,
pageJumpLabel: 'Go to page',
});
// Remove the application override when no longer needed.
// tablePagination.unregister('example.stores');Registrations notify mounted tables. Explicit table.pagination takes precedence
over registration. Page jumps accept only integer pages in the known page range;
the control is disabled when the page count is unavailable.
In AutoCrudTable, the jump label follows the existing locale unless explicitly overridden.
Set responsive: true alongside these options to hide the extra controls when
their measured content does not fit the pagination container. This responds to
container resizing and translated text widths, without changing other tables.
保存视图与动态标签
视图默认关闭。在 QueryClientProvider 内配置存储服务后,通过 table={{ views: true }} 为带稳定 id 的 AutoCrudTable 开启视图菜单:
import {
AutoCrudProvider,
AutoCrudTable,
createLocalViewStorage,
} from '@wordrhyme/auto-crud';
// 服务对象应保持引用稳定。后端存储实现 ViewStorage 的四个必需方法,可选实现 getCapabilities / reorder。
const viewStorage = createLocalViewStorage(`${organizationId}:${userId}`);
<QueryClientProvider client={queryClient}>
<AutoCrudProvider
scope={`${organizationId}:${userId}`}
viewStorage={viewStorage}
tagService={tagService}
>
<AutoCrudTable
id="crm.customers"
table={{ views: true }}
schema={schema}
resource={resource}
fields={{
tags: { label: '分类', filter: { variant: 'tags' }, form: false },
}}
/>
</AutoCrudProvider>
</QueryClientProvider>;- 视图保存筛选条件、条件间的 AND/OR、搜索词和排序;不保存分页、选中行。支持新建、复制、重命名、删除、保存和放弃修改。省略
views或传false时关闭,传true或配置对象时开启。独立AutoTable使用views={true},并提供稳定的resourceId。全局viewStorage和本地展示偏好不会自动开启视图。之前依赖自动开启的列表需补充table={{ views: true }}。 - 视图支持下拉与 Tab 两种展示:下拉放在搜索框前,设置收在下拉菜单内;Tab 放在筛选栏上方,末尾仅提供设置图标,新建操作与下拉模式一致,放在设置菜单内。在设置菜单的“展示方式”中切换,当前视图及未保存修改会保留。有修改时显示状态点、允许的保存操作和“还原”;固定预设或只读视图通过“另存为新视图”保留修改。无本地偏好时默认使用下拉;
table={{ views: { selector: 'tabs' } }}可设置初始展示。独立使用AutoTable时传views={{ selector: 'tabs' }}。本地记忆优先于selector,展示方式不写入已保存的查询。 scope必须包含当前用户与租户;切换时重置组件状态。createLocalViewStorage仅保存当前浏览器中的视图。换用后端时传入ViewStorage,组件调用方式不变。TagService.list接收resourceId/field和可选的query/page/pageSize/signal,统一返回{ options: TagOption[], hasMore: boolean },两个字段都必须提供。每个选项包含稳定 IDvalue、名称label和颜色color。resolve返回指定稳定 ID 对应的名称与颜色。用户新建标签只增加选项,不增加 schema 字段。create/update/remove/assign是可选能力。assign必须只添加或移除指定标签,保留其他关联;单条编辑和选中行批量设置共用此方法。权限必须由服务端校验。- 标签列默认只展示标签,不自动添加行内或批量编辑按钮。入口由业务通过
actions.row、actions.batch、工具栏或自定义单元格配置;文字、图标及样式使用现有按钮组件控制。 - 标签查询条件形如
{ include: ['vip'], exclude: ['blocked'], match: 'any' }。any/all只作用于正选标签,反选始终要求全部不包含;整个标签条件再参与外层 AND/OR。空条件不进入 URL。 - 标签 ID 通过 JSON 和
__op=matches写入 URL;普通条件沿用现有可读格式。标签重命名不会破坏视图。失效 ID 保留在界面,服务端应拒绝失效条件,避免查询范围意外扩大。 - 后端个人视图须按用户、租户和 CRUD
id隔离;组织视图按租户和 CRUDid隔离,组织成员可见性和管理权限由 Host 校验。标签及其数据关联按租户、CRUDid和字段隔离。视图不是权限凭证。
ViewStorage 和 TagService 的完整 TypeScript 接口由包导出。完整交互示例见 Storybook 的 Auto CRUD / Saved views and tags;可切换 simple、advanced、command 三种模式。
展示方式、当前选中视图的 ID、显示顺序 viewOrder 和隐藏视图 ID hiddenViewIds 自动存入浏览器 localStorage,键为 auto-crud:view-preferences:${encodeURIComponent(scope)}:${encodeURIComponent(resourceId)},按用户/租户和资源隔离,独立于 ViewStorage 的本地或服务端实现。旧偏好无需手动迁移:缺少的新字段表示使用配置顺序、不隐藏视图;浏览器内旧的 hiddenPresetIds 会自动转换为 hiddenViewIds,已有新字段时以新字段为准。刷新或重新进入时恢复展示偏好;视图列表加载成功后恢复选中项。URL 已有筛选、搜索、排序或分页参数时保留 URL 查询,否则应用上次视图的保存条件,使用 replace 更新 URL。上次视图已删除、已隐藏或字段不可用时清除其选中记忆,保留 URL 查询。本地数据损坏或存储不可用时使用配置的初始展示方式,仍可在当前页面调整显示偏好。未保存的查询不另存到本地偏好中。
代码预设与 Host 保存范围
预设通过已有 SavedViewsConfig.presets 传入,业务方用数组组合默认项与扩展项;无需写入数据库。独立 AutoTable 通过 views.presets 传入同样配置。
import type { PresetView, ViewStorage } from '@wordrhyme/auto-crud';
const shopPresets: PresetView[] = [
{
id: 'shop:pending-orders',
name: '待处理订单',
slug: 'pending-orders',
query: { filters: [], joinOperator: 'and', search: 'pending', sort: [] },
},
];
// 扩展方只增加自己的稳定 ID / slug,不覆盖 Shop 项。
const presets = [...shopPresets, ...omniDsPresets];
const viewStorage: ViewStorage = {
list: (resourceId) => api.views.list({ resourceId }),
getCapabilities: (resourceId) => api.views.capabilities({ resourceId }),
create: (resourceId, input) => api.views.create({ resourceId, ...input }),
update: (resourceId, id, input) => api.views.update({ resourceId, id, ...input }),
remove: (resourceId, id) => api.views.remove({ resourceId, id }),
};
<AutoCrudProvider scope={`${organizationId}:${userId}`} viewStorage={viewStorage}>
<AutoCrudTable
id="shop.orders"
schema={schema}
resource={resource}
table={{ views: { presets, defaultView: 'pending-orders', counts: loadViewCounts } }}
/>
</AutoCrudProvider>;默认合并顺序为“全部 → presets 数组顺序 → storage.list 返回顺序”,随后应用个人显示顺序和隐藏偏好。ID、slug 在合并后的所有来源间共用命名空间:重复 ID、重复 slug 或 slug 与另一项 ID 相同均报错,禁止静默覆盖。预设 schema 不接受 scope 或 capabilities;其来源由组件根据配置入口识别。预设可隐藏、恢复和调整本地显示顺序;其查询仍由代码维护,不可保存覆盖、重命名、删除或参与存储排序,修改查询后可另存为普通持久化视图并取得新的 ID / slug。隐藏项仍参与 ID / slug 冲突校验。Host 应在服务端预留代码预设的 ID / slug,防止其他调用方或并发写入产生冲突。
复用基础页面时,可通过 views.hiddenViews?: readonly string[] 按 ID 或 slug 隐藏任意来源的视图,无需修改查询定义。例如通过已知 slug 提前隐藏 WordRhyme 订单预设「已付款」:
<AutoCrudTable
id="shop.orders"
schema={schema}
resource={resource}
table={{
views: {
presets,
hiddenViews: ['shop-orders-paid'],
selector: 'tabs',
tabs: { variant: 'line' },
},
}}
/>独立 AutoTable 同样使用 views={{ presets, hiddenViews }}。省略或传空数组表示页面不额外隐藏;数组可混用 ID 与 slug,按大小写精确匹配,不按显示名称匹配。ID 与 slug 已在同一资源内共用唯一命名空间,不会歧义匹配。重复项被忽略,暂未匹配的项不影响加载,视图之后注册或创建并出现在可见集合时自动应用配置;没有 slug 的视图仍可用 ID。修改 slug 后需同步更新对应配置,用户在界面上隐藏时继续按稳定 ID 保存本地偏好。预设、个人及只读共享视图均可隐藏,“全部”仍固定可见。页面配置的隐藏与用户本地隐藏取并集,配置项不进入“恢复隐藏视图”菜单;移除配置后,若用户未自行隐藏该项,就会重新显示。配置本身不写入本地偏好、不修改查询定义、不调用 ViewStorage 写入方法,也不是访问权限控制。
运行时新增配置使当前选中项被隐藏时,会切换到“全部”并重置查询;初始化时不会选中已隐藏的默认项或本地记忆项。显式 URL 指向配置隐藏项时提示页面已隐藏该视图并保留 URL 查询,不提供用户恢复入口。隐藏项不参与可见视图的数量统计,但仍参与 ID / slug 冲突校验。Storybook 的 Configured Hidden Views 可通过 hiddenViews 控件体验 ID / slug 混用及移除配置后的显示。
基础页面必须将消费侧配置传入 table.views。WordRhyme 当前的 registerViews(id, views) 只追加预设数组;仅在 OmniDS 插件侧传入隐藏视图的 ID 或 slug 尚不会生效,需由 WordRhyme 的扩展配置入口接收并透传到此处,查询定义继续留在基础项目。
公共 schema 和对应类型均从包导出:viewQuerySchema / ViewQuery、viewInputSchema / ViewInput、savedViewSchema / SavedView、presetViewSchema / PresetView、viewScopeSchema / ViewScope、viewCapabilitiesSchema / ViewCapabilities、viewStorageCapabilitiesSchema / ViewStorageCapabilities。
type ViewScope = string; // Host 定义的非空标识,最长 80 字符。
// 原有 name / slug? / query 保持不变。
type ViewInput = { name: string; slug?: string; query: ViewQuery; scope?: ViewScope };
type SavedView = ViewInput & {
id: string;
capabilities?: { update: boolean; delete: boolean; reorder: boolean };
};
type ViewStorageCapabilities = { createScopes: ViewScope[] };
// list 继续返回 SavedView[],不会变为分页或包含 capabilities 的包装对象。
// 这些值及其可见性由 Host 定义,组件不解释其业务含义。
const views: SavedView[] = [
{
id: 'org:1',
name: '共享订单',
query,
scope: 'organization',
capabilities: { update: false, delete: false, reorder: false },
},
{
id: 'mine:1',
name: '我的订单',
query,
scope: 'personal',
capabilities: { update: true, delete: true, reorder: true },
},
];
// getCapabilities(resourceId) 返回可用保存范围,第一项为默认;[] 表示不可创建。
const capabilities: ViewStorageCapabilities = {
createScopes: ['personal', 'organization'],
};scope是 Host 的不透明存储标识,组件不内置个人/组织枚举、展示文案或权限推断。个人/组织的可见性、归属及服务端授权由 Host 实现。AutoCrudProvider.scope仍是用户/租户缓存及偏好命名空间,与视图保存范围不同。- 创建省略
scope使用存储适配器默认值;更新省略时保留原范围。更新不能迁移范围,要改变范围请另存。提供getCapabilities时,组件默认选择返回列表的第一项。Host 可继续使用personal/organization,通过返回顺序定义默认行为。 - 保存弹窗默认只显示名称和 slug。业务需要让用户选择保存范围时,配置
views.scopeOptions: [{ value, label }];值与createScopes取交集,只有多个可用选项时才展示选择器,文案完全由调用方提供。配置后以首个可用配置项为默认;未配置或只有一个选项时隐藏选择器,仍向适配器传入选定范围。 capabilities.update同时控制保存查询、重命名和修改 slug;delete控制删除;reorder表示适配器层面的持久化排序权限,不限制个人本地显示顺序。提供 capabilities 时三个布尔值都必须返回。省略时保留旧适配器的可管理行为;Host 必须为有权限差异的项显式返回能力。组件不根据 scope、角色或身份猜权限。getCapabilities?: (resourceId: string) => Promise<ViewStorageCapabilities>为独立异步读取,不影响 list 的返回形状。旧适配器省略时允许创建且不指定范围;已实现时加载或失败均禁用创建,失败提供重试。Host 需返回当前资源实际允许的范围,在每次写入时再次校验权限。组件成功写入后刷新列表和创建能力。- 所有来源共用现有 URL、默认选中、本地偏好、
fieldsReady、Tab 和异步 counts 机制;范围不写入查询。createLocalViewStorage在给定的浏览器命名空间内保存视图,scope 如有提供则原样保存,不实现跨用户共享。
// Host 可选配置:选项的含义和文案由业务决定。
table={{ views: {
scopeOptions: [
{ value: 'personal', label: '仅自己' },
{ value: 'organization', label: '共享' },
],
} }}之前通过 scope 自动推断只读的适配器,需改为显式返回 capabilities。既有 Host 的 list / create / update / remove / reorder 和 getCapabilities 形状保持不变;未配置 scopeOptions 时不展示范围选择器。
Storybook 的 Presets And Shared Views 展示两组代码预设、只读项和可编辑项,可体验任意项隐藏/恢复与混合排序;Organization Administrator 演示由 Host 注入“仅自己/共享”选项和权限。示例 Host 的查询定义使用内存存储,刷新重置;个人显示偏好在当前浏览器保留,不代表浏览器本地存储提供共享能力。
共享视图示例使用 queryKeys.view: 'sharedView',普通示例继续使用 view。切换这两组数据源时,示例会清理另一组的视图参数及关联查询,避免 Storybook 保留的旧 URL 指向不同存储中的视图;同组刷新与分享链接仍保留当前查询。
默认视图、分享链接与排列顺序
<AutoCrudTable
id="crm.customers"
schema={schema}
resource={resource}
table={{
views: { defaultView: 'vip-customers', selector: 'tabs' },
// 可选;同页多个列表或字段名与 view 冲突时使用不同的 URL 参数名。
queryKeys: { view: 'customerView' },
}}
/>defaultView 接受视图的 slug 或 ID,独立 AutoTable 使用 views={{ defaultView: 'vip-customers' }}。初始化优先级为 URL 指定、用户本地选中记忆、defaultView、全部;本地明确记住“全部”也优先于默认值。默认项不存在时回到全部,不自动选择其他视图。views 仍须显式开启,本地偏好与 URL 都不会自动开启视图功能。
视图可包含可选的 slug,例如 { id: 'view-123', slug: 'vip-customers', name: '重点客户', query }。新建时按名称建议 slug,可手动修改;重命名保持原 slug。slug 为 1–80 个文字、数字或连接用的短横线,区分大小写。ViewStorage.create/update 须保存并返回该字段,update 未传 slug 时保留原值;已有数据无需迁移,没有 slug 时继续使用 ID。同一资源内 ID 和 slug 必须唯一,slug 也不能与另一视图的 ID 相同。服务端须保证同一用户可见的预设、组织和个人项之间引用无冲突;修改 slug 后旧 slug 链接失效,稳定 ID 仍可定位。
默认参数为 ?view=vip-customers,也接受 ?view=view-123;若配置上例的 queryKeys.view,则使用 ?customerView=vip-customers。切换视图会同步参数并创建浏览器历史记录,前进/后退恢复 URL 指定的视图。有 slug 时写入规范 slug,只有 ID 的旧链接会以 replace 规范化。?view= 明确表示“全部”。仅带视图参数的链接会应用保存条件;若同时带筛选、搜索、排序或分页参数,保留完整 URL 查询,便于分享未保存的调整。无权访问、已删除或查询字段失效时显示错误并保留 URL 查询,不回退到另一个视图。链接接收者仍需有权限读取该视图及资源,URL 不授予访问权限。
下拉和 Tab 共用个人显示偏好,“全部”固定在最前,不参与隐藏或排序。设置菜单始终提供“调整顺序”:至少有两个可见视图且列表加载成功后可用,拖动手柄(也支持键盘)后点击保存,取消不会改变顺序或当前选中项。预设与所有已保存项(包括只读共享项)均可混合调整显示顺序,无需实现 ViewStorage.reorder,也不受 capabilities.reorder 限制;操作仅写本地偏好,不调用服务端排序、不改变他人的顺序、共享查询或存储权限。列表加载失败或配置冲突时禁用;创建权限加载失败仅禁用创建,不阻止已成功加载列表的本地排序。
选择任意视图后,在“视图设置 → 隐藏视图”中隐藏;隐藏当前项会切换到“全部”,清空筛选、搜索和排序并重置分页。通过“恢复隐藏视图”子菜单逐项恢复,不自动选中。隐藏项的位置在调整其他视图时保留,恢复后回到该位置。本地隐藏适用于预设、个人和只读共享视图,不受 capabilities.update/delete/reorder 限制;共享查询定义及编辑/删除权限保持原有语义。defaultView 或上次选中记忆不会重新选择隐藏项;显式 URL 指向用户隐藏项时显示恢复提示并保留 URL 查询,恢复后可继续使用该链接。
顺序按稳定 ID 记录;重复或不在当前集合中的 ID 被忽略,新增项按代码/存储默认顺序追加。暂时不可见或插件移除的项不阻止加载,隐藏 ID 会保留供插件恢复时使用。排序弹窗打开后若可见集合变化,保存会提示重新调整,避免漏掉新项。切换展示方式、选中视图或保存查询均保留显示顺序与隐藏偏好。本地存储不可用时,本轮页面内的调整仍然有效,刷新后可能丢失。
ViewStorage 保留可选的适配器排序接口,供需要管理持久化顺序的调用方使用;视图选择器的“调整顺序”不再调用它:
reorder?: (resourceId: string, ids: string[]) => Promise<void>;直接调用该接口时,ids 仍必须为该资源当前允许排序的持久化项的完整排列,只包含 capabilities.reorder 为 true 的项(旧适配器省略 capabilities 时仍允许排序)。预设和不可排序项从不传入,Host 必须保留其他项在持久化列表中的位置,将新顺序填入可排序项原有位置。例如 list 为 [只读 A, 可排序 B, 可排序 C],提交 [C, B] 后应为 [A, C, B]。服务端应在事务中校验权限并保存,拒绝重复、未知、无权或缺失 ID;并发新增/删除或权限变化导致集合不一致时返回错误。该接口及 createLocalViewStorage 的实现保持兼容,既有存储顺序仍作为没有个人排列偏好时的默认顺序。
Storybook 的 Default View 演示按 slug 默认选中,“视图设置 → 调整顺序”可体验排序;所有 Saved views and tags 示例共用本地视图存储,首次加载补齐演示视图;视图、删除操作和排列顺序刷新后保留。客户标签仍为刷新后重置的内存数据。
标签列表调用示例:
const controller = new AbortController();
const { options, hasMore } = await tagService.list({
resourceId: 'crm.customers',
field: 'tags',
query: '重点',
page: 1,
pageSize: 30,
signal: controller.signal,
});
// options: [{ value: 'vip', label: '重点客户', color: '#3b82f6' }]
// hasMore: false标签选择器从第 1 页开始,每页请求 30 项,搜索为空时传 query: '';搜索变化后重新请求第 1 页。服务应将 signal 传给底层请求以支持取消,读取失败时抛出异常,由组件显示错误。无结果时返回 { options: [], hasMore: false },最后一页仍返回当前页的选项并设置 hasMore: false。
迁移旧的标签适配器时,移除对 type/values/search 的依赖,搜索统一使用 query;原先返回数组或省略分页字段的实现需要改为上述对象格式,并为选项提供 color。
视图数量
通过可选的 views.counts 回调接入数量,Tab 和下拉选项都会显示。组件提供所有可见视图(预设、组织和个人项)保存的筛选、AND/OR 与搜索条件,并额外提供不带筛选的「全部」查询;查询不包含排序和分页,也不叠加当前尚未保存的筛选。统计独立异步执行,列表不等待统计完成。
import type { SavedViewsConfig } from '@wordrhyme/auto-crud';
// 在组件外定义,或通过 useCallback 保持引用稳定。
const loadViewCounts: NonNullable<SavedViewsConfig['counts']> = async ({
queries,
signal,
}) => {
const result = await api.customers.counts.query({ queries }, { signal });
return result.counts;
};
<AutoCrudTable
id="crm.customers"
schema={schema}
resource={resource}
table={{ views: { selector: 'tabs', counts: loadViewCounts } }}
/>;回调返回以传入 query.key 为键的数量对象,键由组件生成,直接原样返回即可。每批最多 100 个查询,更多视图自动分批。使用 auto-crud-server 时开启 counts: true,数据库适配器须支持受权限和租户范围约束的 $counts;其他后端可自行实现相同的回调。
首次加载显示 …,零结果显示 0,缺失或无效数量显示 —,请求失败显示 — 和重试入口。保存视图条件或更换 counts 回调会重新统计。配合 useAutoCrudResource 时,翻页、排序和切换视图复用已有数量。成功写入、显式刷新资源或当前列表的行数据更新后,角标会刷新。独立 AutoTable 使用 views={{ selector: 'tabs', counts: loadViewCounts }},行数组引用变化时刷新。数量保存在查询缓存中。
Storybook 的 Auto CRUD / Saved views and tags / Tabs With Counts 与其他视图示例共用本地视图存储,模拟 300ms 统计请求延迟;首次加载预置数量为 3、2、1、0 的视图。列表和数量共用筛选逻辑,修改客户标签后会重新计算。视图与排列顺序刷新后保留,客户标签刷新后重置。
视图 Tab 样式
views.tabs 控制 Tab 外观。默认使用现有的分段样式;variant: 'line' 显示选中项的强调线,linePosition 支持 bottom(默认)和 top。下拉展示不受此配置影响。
<AutoCrudTable
id="crm.customers"
schema={schema}
resource={resource}
table={{
views: {
selector: 'tabs',
tabs: {
variant: 'line',
classNames: {
list: 'gap-2',
trigger: 'text-base data-[state=on]:text-blue-700',
indicator: 'h-1 bg-blue-600',
},
},
},
}}
/>classNames.list 作用于 Tab 列表,trigger 作用于每个 Tab(含「全部」),indicator 作用于选中项的线条,可修改颜色和粗细。类名通过 cn 在默认类名之后合并;trigger 的选中状态可用 data-[state=on] 定制。linePosition 和 indicator 仅在线条样式中生效。独立 AutoTable 使用同样的 views.tabs 配置。这些外观配置由使用方提供,不写入本地偏好。
Storybook 提供 Line Tabs(下方蓝色强调线)和 Top Line Tabs(上方强调线)示例,均带预设、共享视图和数量;选中后可在齿轮菜单隐藏、恢复或调整顺序,也可通过 Controls 切换样式和线条位置。已有本地展示偏好时,仍可在视图设置中切换到 Tab。
自动标签接入
字段声明 tags: true 后,AutoCrudTable 自动展示标签、启用标签筛选,并生成行操作和批量操作的设置入口:
const schema = z.object({
id: z.string(),
recordTags: z.array(z.string()).optional(),
});
<AutoCrudTable
id="crm.customers"
schema={schema}
resource={resource}
permissions={permissions}
fields={{ recordTags: { label: '标签', form: false, tags: true } }}
/>;应用级 AutoCrudProvider 提供 tagService,页面无需再维护 TagAssignment、弹窗状态或选中记录转换。资源 ID 复用表格 id,记录主键复用 resource.idKey(默认 id),保存后调用 resource.handlers.refresh。未填写的标签值按空数组处理。
自动入口跟随 permissions.can.update,字段 hidden: true 或被 permissions.deny 禁止时不生成入口;服务未提供 assign 时只展示和筛选。已有行操作、批量操作和注册扩展仍会保留。自动操作的稳定 ID 为 tags:<字段名>,可通过现有操作注册机制调整。locale.tagAssignment 可覆盖入口与弹窗标题。
tags: true 默认补充 filter.variant: 'tags',显式筛选配置优先,filter: false 仍可禁用筛选且保留标签展示和设置入口。省略或设置 tags: false 不生成自动入口,已有 filter.variant: 'tags' 和手动弹窗接入方式保持兼容。标签仍由现有服务读写,无需新增页面接口或业务表。
自定义标签编辑入口
TagAssignment 是受控弹窗,不包含按钮。打开后直接显示搜索和标签列表,已有标签默认选中,通过勾选/取消勾选编辑,无需选择添加或移除。已选标签的名称、颜色实时显示;清空和保存位于同一行,点击保存后才提交记录的标签关联。
筛选列表和赋值列表均在底部提供「添加标签」,每个标签后的编辑图标直接在当前行编辑名称、颜色。编辑区使用确认/取消图标,并在有删除权限时提供删除和行内确认;没有独立的管理弹窗。新建、重命名、改色、删除标签定义会立即调用对应服务并刷新标签缓存,与底部保存记录勾选结果分别提交。仅配置服务已提供的能力对应的入口;编辑标签定义期间暂停勾选和保存记录,避免未完成的编辑丢失。
在同一个 AutoCrudProvider 和 QueryClientProvider 内渲染,resourceId 与表格 id 一致。entities 传入 { id, tagIds } 数组,组件在打开时保存当前标签快照:单条记录默认勾选已有标签;多条记录的共同标签全选,部分记录才有的标签半选。未操作的半选标签保持原样,勾选后给所有记录设置,取消勾选后从所有记录移除;清空会清除所选记录的所有已有标签。只有存在实际变化时才能保存,底层仍通过 TagService.assign 提交增删差异,保留其他标签。
保存成功后刷新标签缓存,调用 onSaved,最后通过 onOpenChange(false) 请求关闭;失败时保留弹窗并显示错误,提交期间禁用选择操作。关闭后放弃未提交选择,再次打开使用新的当前标签;打开期间切换资源、字段或目标记录时重建编辑状态。未提供 tagService.assign 时不渲染弹窗。
import { useState } from 'react';
import { Tags } from 'lucide-react';
import { Button } from '@wordrhyme/shadcn';
import { TagAssignment, type TagAssignmentProps } from '@wordrhyme/auto-crud';
function EditTags({
entities,
onSaved,
}: {
entities: TagAssignmentProps['entities'];
onSaved: () => void | Promise<void>;
}) {
const [open, setOpen] = useState(false);
return (
<>
