@hzab/list-render 1.10.19 → 1.10.20-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,217 @@
1
+ import React, { useState, useCallback, useRef } from "react";
2
+ import { Button } from "antd";
3
+ import { createSchemaField } from "@formily/react";
4
+ import { cloneDeep } from "lodash";
5
+
6
+ import { useSlotsComponents } from "../useComponents";
7
+
8
+ import { Item } from "./type";
9
+
10
+ export const useEditTable = (props) => {
11
+ const { rowFormMapRef, editingInofRef, topProps, idKey, columns, onEditSubmit } = props;
12
+ const { editMode = "modal", Slots } = topProps || {};
13
+ const preIdRef = useRef("");
14
+ const preIdxRef = useRef(null);
15
+ const preRecordRef = useRef({});
16
+
17
+ // 创建 formily 表单相关参数
18
+ /** schema scope 解决父级无 schema Scope 导致 scope 对象刷新的问题 */
19
+ const schemaScopeRef = useRef<{ _$tempData: Object }>();
20
+ if (props.schemaScope && !schemaScopeRef.current) {
21
+ schemaScopeRef.current = props.schemaScope;
22
+ } else if (!schemaScopeRef.current) {
23
+ schemaScopeRef.current = { _$tempData: {} };
24
+ }
25
+ if (!schemaScopeRef.current?._$tempData) {
26
+ schemaScopeRef.current._$tempData = {};
27
+ }
28
+
29
+ const components = useSlotsComponents(topProps);
30
+
31
+ const SchemaField = useCallback(
32
+ createSchemaField({
33
+ components,
34
+ scope: {
35
+ scenario: "tableRowForm",
36
+ ...schemaScopeRef.current,
37
+ },
38
+ }),
39
+ [],
40
+ );
41
+
42
+ // 是否可编辑状态逻辑处理
43
+ const [editingId, setEditingId] = useState("");
44
+ // 当前编辑的字段
45
+ const [editingKey, setEditingKey] = useState("");
46
+ /** 判断当前 行 是否处于编辑状态 */
47
+ const isEditing = (record: Item) => record[idKey] === editingId;
48
+ /** 判断当前 单元格 是否处于编辑状态 */
49
+ const isEditingCell = (key) => key === editingKey;
50
+ const editingFiledRef = useRef(null);
51
+
52
+ // useEffect(() => {
53
+ // if (editingId || editingKey) {
54
+ // // HACK: try catch 解决 select 等表单项 focus 报错问题
55
+ // try {
56
+ // // HACK: setTimeout 解决执行先后顺序导致无法正常获取 dom 问题
57
+ // setTimeout(() => {
58
+ // editingFiledRef.current?.current?.focus?.();
59
+ // }, 0);
60
+ // } catch (error) {}
61
+ // }
62
+ // }, [editingId, editingKey]);
63
+
64
+ /**
65
+ * 点击编辑按钮
66
+ * @param record
67
+ */
68
+ const onEdit = async (record: Partial<Item> & { key: React.Key }, key, opt = { fieldRef: null, index: null }) => {
69
+ if (editMode == "modal") {
70
+ return;
71
+ }
72
+ const { fieldRef } = opt || {};
73
+ preRecordRef.current = record;
74
+ const id = record[idKey];
75
+ editingInofRef.current.editingRowId = id;
76
+ editingInofRef.current.editingKey = key;
77
+ const rowForm = rowFormMapRef.current.get(id);
78
+ rowForm.readPretty = false;
79
+ editingFiledRef.current = fieldRef;
80
+ rowForm.values = record;
81
+ rowForm?.setValues(record);
82
+ preIdRef.current = id;
83
+ preIdxRef.current = opt.index;
84
+ setEditingId(id);
85
+ setEditingKey(key);
86
+ };
87
+
88
+ /**
89
+ * 点击编辑按钮
90
+ * @param record
91
+ */
92
+ const onEditAFetch = async (record: Partial<Item> & { key: React.Key }, key, opt) => {
93
+ if (editMode == "modal") {
94
+ return;
95
+ }
96
+ const value = await (props.onEdit && props.onEdit(record));
97
+ preRecordRef.current = value;
98
+ preIdRef.current = record[idKey];
99
+ preIdxRef.current = opt.index;
100
+ onEdit.call(this, value, key, opt);
101
+ };
102
+
103
+ function onCancel() {
104
+ onReset();
105
+ setEditingId("");
106
+ setEditingKey("");
107
+ preRecordRef.current = {};
108
+ preIdRef.current = "";
109
+ editingFiledRef.current = null;
110
+ }
111
+
112
+ function onReset() {
113
+ const preRowForm = rowFormMapRef.current.get(preIdRef.current);
114
+ if (preRowForm) {
115
+ // disabled 后设置会导致 readPretty 设置失效
116
+ preRowForm.disabled = true;
117
+ preRowForm.readPretty = true;
118
+ // 取消数据重置为编辑前数据
119
+ preRowForm.reset();
120
+ preRowForm.values = preRecordRef.current;
121
+ preRecordRef.current = {};
122
+ editingInofRef.current.editingRowId = "";
123
+ editingInofRef.current.editingKey = "";
124
+ }
125
+ }
126
+
127
+ /**
128
+ * 保存数据
129
+ * field 当前编辑的项
130
+ * 当前数据的 id
131
+ */
132
+ const onEditSave = async ({ field, id, dataIndex }) => {
133
+ const rowForm = rowFormMapRef.current.get(id);
134
+ try {
135
+ // 点击保存,数据抛出
136
+ (await rowForm?.validate()) as Item;
137
+ onEditSubmit && (await onEditSubmit(rowForm.values, { field, id, dataIndex }));
138
+ // 清除编辑目标
139
+ setEditingId("");
140
+ setEditingKey("");
141
+ rowForm.disabled = true;
142
+ rowForm.readPretty = true;
143
+ onReset();
144
+ } catch (errInfo) {
145
+ console.error("Validate Failed:", errInfo);
146
+ }
147
+ };
148
+
149
+ const mergedColumns = cloneDeep(columns)?.map((col) => {
150
+ const isActions = col.key === "_$actions";
151
+ if (!col.editable && !isActions) {
152
+ return col;
153
+ }
154
+
155
+ const resCol = {
156
+ ...col,
157
+ onCell: (record: Item, ...args) => {
158
+ let editing = false;
159
+ if (editMode === "cell") {
160
+ editing = isEditing(record) && isEditingCell(col.dataIndex);
161
+ } else {
162
+ editing = isEditing(record);
163
+ }
164
+ return {
165
+ ...(col.onCell ? col.onCell(record, ...args) : {}),
166
+ record,
167
+ components,
168
+ SchemaField,
169
+ // 函数获取解决 cloneDepp 报错问题
170
+ getField: col.getField,
171
+ dataIndex: col.dataIndex,
172
+ title: col.title,
173
+ editable: col.editable,
174
+ editing,
175
+ topProps: props.topProps,
176
+ onEdit: onEditAFetch,
177
+ onEditSave,
178
+ onCancel,
179
+ };
180
+ },
181
+ };
182
+ // 操作列编辑态改成保存、取消按钮
183
+ if (isActions) {
184
+ resCol.render = (record, index) => {
185
+ // 编辑态操作栏变成保存和取消按钮
186
+ if (editMode === "line" && record[idKey] === editingId) {
187
+ return (
188
+ <div className="edit-table-actions">
189
+ <Button
190
+ type="link"
191
+ onClick={() => {
192
+ onEditSave({ field: undefined, dataIndex: undefined, id: record[idKey] });
193
+ }}
194
+ >
195
+ 保存
196
+ </Button>
197
+ <Button type="text" onClick={onCancel}>
198
+ 取消
199
+ </Button>
200
+ </div>
201
+ );
202
+ }
203
+ return col.render(record, index);
204
+ };
205
+ }
206
+ return resCol;
207
+ });
208
+
209
+ return {
210
+ onEditAFetch,
211
+ onEdit,
212
+ onEditSave,
213
+ onEditCancel: onCancel,
214
+ SchemaField,
215
+ mergedColumns,
216
+ };
217
+ };
@@ -0,0 +1,6 @@
1
+ export interface Item {
2
+ id: string;
3
+ key: string;
4
+ }
5
+
6
+ export type EditMode = "modal" | "line" | "line-cell" | "cell" | "table-edit" | "table-edit-show";
@@ -0,0 +1,17 @@
1
+ import { createContext, useContext } from "react";
2
+
3
+ interface TableFormilyContextType {
4
+ rowFormMapRef;
5
+ editingInofRef;
6
+ }
7
+
8
+ // 创建行上下文
9
+ export const TableFormilyContext = createContext<TableFormilyContextType | null>(null);
10
+
11
+ export const useTableFormilyContext = () => {
12
+ const context = useContext(TableFormilyContext);
13
+ if (!context) {
14
+ throw new Error("useTableFormilyContext must be used within TableFormilyContext.Provider");
15
+ }
16
+ return context;
17
+ };
@@ -0,0 +1,270 @@
1
+ import { cloneDeep } from "lodash";
2
+ import { nanoidNumALetters } from "@hzab/utils/src/nanoid";
3
+ import { Schema } from "@formily/json-schema";
4
+
5
+ /**
6
+ * 普通的 schema 表单字段转为自增表格的列
7
+ * @returns
8
+ */
9
+ export class SchemaToArrayTable {
10
+ _schema: {
11
+ form: {};
12
+ schema: Schema;
13
+ };
14
+ config = {};
15
+ topProps = {};
16
+ constructor(params) {
17
+ const { schema, config, topProps } = params || {};
18
+ this._schema = cloneDeep(schema);
19
+ this.config = config || {};
20
+ this.topProps = topProps || {};
21
+ }
22
+ /**
23
+ * 处理 schema,把普通的 schema 表单字段转为自增表格的列
24
+ * @returns
25
+ */
26
+ handleSchema(schema = this._schema, opt?) {
27
+ const { isDargTable, hasAction, hasIndex } = opt || this.config;
28
+ const schemaTpl = this.getSchemaTpl(this.config);
29
+ const properties: Record<string, any> = {};
30
+ // schema 布局信息
31
+ schemaTpl.form = {
32
+ ...schema.form,
33
+ };
34
+
35
+ // 添加拖拽排序列
36
+ isDargTable && this.pushItem(properties, this.getSortTpl());
37
+ // 添加序号
38
+ hasIndex && this.pushItem(properties, this.getIndexTpl());
39
+ // 处理表单数据列
40
+ Object.keys(schema.schema?.properties).forEach((key, i) => {
41
+ const it = schema.schema?.properties[key];
42
+ // @ts-ignore
43
+ if (it.inTable === false) {
44
+ return;
45
+ }
46
+ this.pushItem(properties, this.handleCol(it));
47
+ });
48
+ // 添加操作列
49
+ hasAction !== false && this.pushItem(properties, this.getActionsTpl());
50
+ // 添加移动排序操作列
51
+ // isDargTable && this.pushItem(properties, this.getMoveActionsTpl());
52
+
53
+ schemaTpl.schema.properties.arrayTable.items.properties = properties;
54
+
55
+ return schemaTpl;
56
+ }
57
+ /**
58
+ * 处理列的数据
59
+ * @param {*} item
60
+ * @param {*} idx
61
+ * @returns
62
+ */
63
+ handleCol(item, idx = 0) {
64
+ const id = `${item.name}-${nanoidNumALetters()}`;
65
+ const _item = cloneDeep(item);
66
+ _item.title = "";
67
+ return {
68
+ type: "void",
69
+ "x-component": "ArrayTable.Column",
70
+ "x-component-props": {
71
+ title: item.title,
72
+ },
73
+ "x-designable-id": id,
74
+ name: id,
75
+ "x-index": idx,
76
+ properties: {
77
+ [item.name]: _item,
78
+ },
79
+ };
80
+ }
81
+ /**
82
+ * 在 properties 中指定序号添加一项
83
+ * @param {*} properties
84
+ * @param {*} item
85
+ * @param {*} idx
86
+ */
87
+ addItem(properties, item, idx) {
88
+ // 数组存放实际顺序
89
+ const arr = [];
90
+ // 获取当前排序的数组
91
+ Object.keys(properties).forEach((key) => {
92
+ const it = properties[key];
93
+ arr[it["x-index"]] = it;
94
+ });
95
+ // 在指定位置添加项
96
+ arr.splice(idx, 0, item);
97
+ // 根据数组顺序更新源数据
98
+ arr.forEach((it) => {
99
+ properties[it.name] = it;
100
+ });
101
+ return properties;
102
+ }
103
+ /**
104
+ * 在 properties 中添加一项
105
+ * @param {*} properties
106
+ * @param {*} item
107
+ */
108
+ pushItem(properties, item) {
109
+ properties[item.name] = cloneDeep(item);
110
+ properties[item.name]["x-index"] = Object.keys(properties).length - 1;
111
+ return properties;
112
+ }
113
+ /**
114
+ * 获取 schema 模板字符串
115
+ * @returns
116
+ */
117
+ getSchemaTpl(config) {
118
+ const { onSortStart, onSortEnd } = config || {};
119
+ return {
120
+ form: {},
121
+ schema: {
122
+ type: "object",
123
+ properties: {
124
+ arrayTable: {
125
+ type: "array",
126
+ "x-decorator": "FormItem",
127
+ "x-component": "ArrayTable",
128
+ "x-validator": [],
129
+ "x-component-props": {
130
+ // TODO: ts
131
+ // @ts-ignore
132
+ ...this.topProps.tableProps,
133
+ pagination: false,
134
+ onSortStart(...args) {
135
+ onSortStart && onSortStart(...args);
136
+ },
137
+ onSortEnd(...args) {
138
+ onSortEnd && onSortEnd(...args);
139
+ },
140
+ },
141
+ "x-decorator-props": {},
142
+ "x-designable-id": "arrayTable",
143
+ "x-index": 0,
144
+ items: {
145
+ type: "object",
146
+ "x-designable-id": "gbmerqeme8g",
147
+ properties: {
148
+ // 自增表格列
149
+ },
150
+ },
151
+ // 新增按钮
152
+ properties: {
153
+ // cs1marpxdon: {
154
+ // type: "void",
155
+ // title: "Addition",
156
+ // "x-component": "ArrayTable.Addition",
157
+ // "x-designable-id": "cs1marpxdon",
158
+ // "x-index": 0,
159
+ // },
160
+ },
161
+ },
162
+ },
163
+ "x-designable-id": "un3pxnx4ong",
164
+ },
165
+ };
166
+ }
167
+ /**
168
+ * 获取排序列模板字符串
169
+ * @returns
170
+ */
171
+ getSortTpl() {
172
+ return {
173
+ name: "sort",
174
+ type: "void",
175
+ "x-component": "ArrayTable.Column",
176
+ "x-component-props": {
177
+ title: "",
178
+ },
179
+ "x-designable-id": "l3z7t4ff7zw",
180
+ "x-index": 0,
181
+ properties: {
182
+ g0cxfnsnevh: {
183
+ type: "void",
184
+ "x-component": "ArrayTable.SortHandle",
185
+ "x-designable-id": "g0cxfnsnevh",
186
+ "x-index": 0,
187
+ },
188
+ },
189
+ };
190
+ }
191
+ getIndexTpl() {
192
+ return {
193
+ name: "index",
194
+ type: "void",
195
+ "x-component": "ArrayTable.Column",
196
+ "x-component-props": {
197
+ title: "序号",
198
+ },
199
+ "x-designable-id": "4ps6b3ut7ft",
200
+ properties: {
201
+ TableIndex: {
202
+ type: "void",
203
+ "x-component": "TableIndex",
204
+ "x-designable-id": "TableIndex",
205
+ "x-index": 0,
206
+ },
207
+ },
208
+ };
209
+ }
210
+ /**
211
+ * 获取操作列模板字符串
212
+ * @returns
213
+ */
214
+ getActionsTpl() {
215
+ return {
216
+ name: "actions",
217
+ type: "void",
218
+ "x-component": "ArrayTable.Column",
219
+ "x-component-props": {
220
+ title: "操作",
221
+ },
222
+ "x-designable-id": "actions",
223
+ properties: {
224
+ tableActions: {
225
+ type: "void",
226
+ "x-component": "TableActions",
227
+ "x-designable-id": "tableActions",
228
+ "x-index": 0,
229
+ },
230
+ },
231
+ };
232
+ }
233
+ /**
234
+ * 获取移动排序操作列模板字符串
235
+ * @returns
236
+ */
237
+ getMoveActionsTpl() {
238
+ return {
239
+ name: "move-actions",
240
+ type: "void",
241
+ "x-component": "ArrayTable.Column",
242
+ "x-component-props": {
243
+ title: "",
244
+ },
245
+ "x-designable-id": "move-actions",
246
+ properties: {
247
+ xynjkn08lvp: {
248
+ type: "void",
249
+ "x-component": "ArrayTable.Remove",
250
+ "x-designable-id": "xynjkn08lvp",
251
+ "x-index": 0,
252
+ },
253
+ gvl20uo8m8q: {
254
+ type: "void",
255
+ "x-component": "ArrayTable.MoveDown",
256
+ "x-designable-id": "gvl20uo8m8q",
257
+ "x-index": 1,
258
+ },
259
+ "4c8wbndejhy": {
260
+ type: "void",
261
+ "x-component": "ArrayTable.MoveUp",
262
+ "x-designable-id": "4c8wbndejhy",
263
+ "x-index": 2,
264
+ },
265
+ },
266
+ };
267
+ }
268
+ }
269
+
270
+ export default SchemaToArrayTable;
@@ -0,0 +1,80 @@
1
+ import { useMemo } from "react";
2
+ import { Card, Slider, Rate } from "antd";
3
+ import { useField, useFieldSchema } from "@formily/react";
4
+
5
+ import { antdComponents, customComponents } from "@hzab/form-render";
6
+ import { getFormilyGlobalComponents } from "@hzab/utils/src/formily/global-components";
7
+ import { useIndex, useRecord } from "@hzab/form-render/src/components/ArrayBase";
8
+
9
+ export const useComponents = (props) => {
10
+ const components = useMemo(
11
+ () => ({
12
+ // Upload,
13
+ Card,
14
+ Slider,
15
+ Rate,
16
+ ...antdComponents,
17
+ ...customComponents,
18
+ ...getFormilyGlobalComponents(),
19
+ ...props.components,
20
+ }),
21
+ [props.components],
22
+ );
23
+
24
+ return components;
25
+ };
26
+
27
+ export const useSlotsComponents = (props) => {
28
+ const { Slots = {} } = props;
29
+
30
+ const components = useComponents(props);
31
+
32
+ const slotsComponents = useMemo(() => {
33
+ const formilyComponents = {
34
+ ...components,
35
+ };
36
+
37
+ const tComs = {
38
+ ...formilyComponents,
39
+ };
40
+
41
+ Object.keys(formilyComponents || {}).forEach((key) => {
42
+ formilyComponents[key] = function (cProps) {
43
+ const field = useField();
44
+ const index = useIndex();
45
+ const record = useRecord();
46
+
47
+ const fieldSchema = useFieldSchema();
48
+ const name = fieldSchema.name;
49
+ const comName = fieldSchema["x-component"];
50
+ const OrigCom = tComs[key];
51
+
52
+ // HACK: ArrayTable.SortHandle 类似写法问题修复
53
+ Object.setPrototypeOf(formilyComponents[key], OrigCom);
54
+
55
+ // 插槽
56
+ const SCom = Slots[name];
57
+ if (key === comName && SCom) {
58
+ const slotProps = {
59
+ ...cProps,
60
+ index,
61
+ record,
62
+ text: cProps.value,
63
+ field: field,
64
+ fieldSchema: fieldSchema,
65
+ /** 原始组件 */
66
+ OrigCom,
67
+ };
68
+ return <SCom {...slotProps} />;
69
+ }
70
+
71
+ return <OrigCom {...cProps} />;
72
+ };
73
+ });
74
+ return formilyComponents;
75
+ }, [components]);
76
+
77
+ return slotsComponents;
78
+ };
79
+
80
+ export default useComponents;
@@ -10,6 +10,7 @@ import axiosI, { isCancel, getCancelTokenSource } from "@hzab/data-model/src/axi
10
10
  import QueryRender from "./query-render";
11
11
  import Pagination from "./pagination-render";
12
12
  import TableRender from "./table-render";
13
+ import EditArrayTable from "./EditArrayTable";
13
14
  import CardRender from "./card-render";
14
15
  import FormModal from "./FormModal";
15
16
  import DetailModal from "./DetailModal";
@@ -202,6 +203,7 @@ const ListRender = forwardRef(function (props, parentRef) {
202
203
  setTotal(res.pagination?.total);
203
204
  props.onGetListEnd && props.onGetListEnd(res);
204
205
  setListLoading(false);
206
+ return res;
205
207
  })
206
208
  .catch((err) => {
207
209
  // 兼容新老版本 data-model isCancel 取法
@@ -454,6 +456,9 @@ const ListRender = forwardRef(function (props, parentRef) {
454
456
  setShowSearch(!showSearch);
455
457
  };
456
458
 
459
+ const CTableRender =
460
+ props.editMode === "table-edit" || props.editMode === "table-edit-show" ? EditArrayTable : TableRender;
461
+
457
462
  return (
458
463
  <div className={`list-render ${props.className}`}>
459
464
  <div className={`list-header ${props.verticalHeader ? "vertical-header" : ""}`}>
@@ -516,10 +521,10 @@ const ListRender = forwardRef(function (props, parentRef) {
516
521
  ) : null}
517
522
 
518
523
  {layout === "default" ? (
519
- <TableRender
524
+ <CTableRender
520
525
  idKey={idKey}
521
526
  ref={tableRef}
522
- schema={schema?.schema}
527
+ schema={schema}
523
528
  list={list}
524
529
  config={props.tableConf}
525
530
  hasAction={props.hasAction}
@@ -540,6 +545,7 @@ const ListRender = forwardRef(function (props, parentRef) {
540
545
  i18n={i18n}
541
546
  onEditSubmit={onEditSubmit}
542
547
  topProps={props}
548
+ handleMessage={handleMessage}
543
549
  />
544
550
  ) : null}
545
551
 
@@ -1,11 +1,11 @@
1
- .pagination-render-wrap {
2
- display: flex;
3
- justify-content: flex-end;
4
- align-items: center;
5
- padding-top: 20px;
6
- .pagination-render {
7
- li {
8
- margin-bottom: 8px;
9
- }
10
- }
11
- }
1
+ .pagination-render-wrap {
2
+ display: flex;
3
+ justify-content: flex-end;
4
+ align-items: center;
5
+ padding-top: 20px;
6
+ .pagination-render {
7
+ li {
8
+ margin-bottom: 8px;
9
+ }
10
+ }
11
+ }