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

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,229 @@
1
+ import React, { useState, useCallback, useRef, useEffect } from "react";
2
+ import { Card, Slider, Rate, Button } from "antd";
3
+ import { createSchemaField } from "@formily/react";
4
+ import { cloneDeep } from "lodash";
5
+
6
+ import { antdComponents, customComponents } from "@hzab/form-render";
7
+ import { getFormilyGlobalComponents } from "@hzab/utils/src/formily/global-components";
8
+
9
+ import { Item, EditMode } from "./type";
10
+
11
+ export const useEditTable = (props) => {
12
+ const { rowFormMapRef, editingInofRef, topProps, idKey, columns, onEditSubmit } = props;
13
+ const { editMode = "modal" } = topProps || {};
14
+ const preIdRef = useRef("");
15
+ const preIdxRef = useRef(null);
16
+ const preRecordRef = useRef({});
17
+
18
+ // 创建 formily 表单相关参数
19
+ /** schema scope 解决父级无 schema Scope 导致 scope 对象刷新的问题 */
20
+ const schemaScopeRef = useRef<{ _$tempData: Object }>();
21
+ if (props.schemaScope && !schemaScopeRef.current) {
22
+ schemaScopeRef.current = props.schemaScope;
23
+ } else if (!schemaScopeRef.current) {
24
+ schemaScopeRef.current = { _$tempData: {} };
25
+ }
26
+ if (!schemaScopeRef.current?._$tempData) {
27
+ schemaScopeRef.current._$tempData = {};
28
+ }
29
+
30
+ const components = {
31
+ // Upload,
32
+ Card,
33
+ Slider,
34
+ Rate,
35
+ ...antdComponents,
36
+ ...customComponents,
37
+ ...getFormilyGlobalComponents(),
38
+ ...props.components,
39
+ };
40
+
41
+ const SchemaField = useCallback(
42
+ createSchemaField({
43
+ components,
44
+ scope: {
45
+ scenario: "tableRowForm",
46
+ ...schemaScopeRef.current,
47
+ },
48
+ }),
49
+ [],
50
+ );
51
+
52
+ // 是否可编辑状态逻辑处理
53
+ const [editingId, setEditingId] = useState("");
54
+ // 当前编辑的字段
55
+ const [editingKey, setEditingKey] = useState("");
56
+ /** 判断当前 行 是否处于编辑状态 */
57
+ const isEditing = (record: Item) => record[idKey] === editingId;
58
+ /** 判断当前 单元格 是否处于编辑状态 */
59
+ const isEditingCell = (key) => key === editingKey;
60
+ const editingFiledRef = useRef(null);
61
+
62
+ // useEffect(() => {
63
+ // if (editingId || editingKey) {
64
+ // // HACK: try catch 解决 select 等表单项 focus 报错问题
65
+ // try {
66
+ // // HACK: setTimeout 解决执行先后顺序导致无法正常获取 dom 问题
67
+ // setTimeout(() => {
68
+ // editingFiledRef.current?.current?.focus?.();
69
+ // }, 0);
70
+ // } catch (error) {}
71
+ // }
72
+ // }, [editingId, editingKey]);
73
+
74
+ /**
75
+ * 点击编辑按钮
76
+ * @param record
77
+ */
78
+ const onEdit = async (record: Partial<Item> & { key: React.Key }, key, opt = { fieldRef: null, index: null }) => {
79
+ if (editMode == "modal") {
80
+ return;
81
+ }
82
+ const { fieldRef } = opt || {};
83
+ preRecordRef.current = record;
84
+ const id = record[idKey];
85
+ editingInofRef.current.editingRowId = id;
86
+ editingInofRef.current.editingKey = key;
87
+ const rowForm = rowFormMapRef.current.get(id);
88
+ rowForm.readPretty = false;
89
+ editingFiledRef.current = fieldRef;
90
+ rowForm.values = record;
91
+ rowForm?.setValues(record);
92
+ preIdRef.current = id;
93
+ preIdxRef.current = opt.index;
94
+ setEditingId(id);
95
+ setEditingKey(key);
96
+ };
97
+
98
+ /**
99
+ * 点击编辑按钮
100
+ * @param record
101
+ */
102
+ const onEditAFetch = async (record: Partial<Item> & { key: React.Key }, key, opt) => {
103
+ if (editMode == "modal") {
104
+ return;
105
+ }
106
+ const value = await (props.onEdit && props.onEdit(record));
107
+ preRecordRef.current = value;
108
+ preIdRef.current = record[idKey];
109
+ preIdxRef.current = opt.index;
110
+ onEdit.call(this, value, key, opt);
111
+ };
112
+
113
+ function onCancel() {
114
+ onReset();
115
+ setEditingId("");
116
+ setEditingKey("");
117
+ preRecordRef.current = {};
118
+ preIdRef.current = "";
119
+ editingFiledRef.current = null;
120
+ }
121
+
122
+ function onReset() {
123
+ const preRowForm = rowFormMapRef.current.get(preIdRef.current);
124
+ if (preRowForm) {
125
+ // disabled 后设置会导致 readPretty 设置失效
126
+ preRowForm.disabled = true;
127
+ preRowForm.readPretty = true;
128
+ // 取消数据重置为编辑前数据
129
+ preRowForm.reset();
130
+ preRowForm.values = preRecordRef.current;
131
+ preRecordRef.current = {};
132
+ editingInofRef.current.editingRowId = "";
133
+ editingInofRef.current.editingKey = "";
134
+ }
135
+ }
136
+
137
+ /**
138
+ * 保存数据
139
+ * field 当前编辑的项
140
+ * 当前数据的 id
141
+ */
142
+ const onEditSave = async ({ field, id, dataIndex }) => {
143
+ const rowForm = rowFormMapRef.current.get(id);
144
+ try {
145
+ // 点击保存,数据抛出
146
+ (await rowForm?.validate()) as Item;
147
+ onEditSubmit && (await onEditSubmit(rowForm.values, { field, id, dataIndex }));
148
+ // 清除编辑目标
149
+ setEditingId("");
150
+ setEditingKey("");
151
+ rowForm.disabled = true;
152
+ rowForm.readPretty = true;
153
+ onReset();
154
+ } catch (errInfo) {
155
+ console.error("Validate Failed:", errInfo);
156
+ }
157
+ };
158
+
159
+ const mergedColumns = cloneDeep(columns)?.map((col) => {
160
+ const isActions = col.key === "_$actions";
161
+ if (!col.editable && !isActions) {
162
+ return col;
163
+ }
164
+
165
+ const resCol = {
166
+ ...col,
167
+ onCell: (record: Item, ...args) => {
168
+ let editing = false;
169
+ if (editMode === "table-line-show") {
170
+ editing = true;
171
+ } else if (editMode === "cell") {
172
+ editing = isEditing(record) && isEditingCell(col.dataIndex);
173
+ } else {
174
+ editing = isEditing(record);
175
+ }
176
+ return {
177
+ ...(col.onCell ? col.onCell(record, ...args) : {}),
178
+ record,
179
+ components,
180
+ SchemaField,
181
+ // 函数获取解决 cloneDepp 报错问题
182
+ getField: col.getField,
183
+ dataIndex: col.dataIndex,
184
+ title: col.title,
185
+ editable: col.editable,
186
+ editing,
187
+ topProps: props.topProps,
188
+ onEdit: onEditAFetch,
189
+ onEditSave,
190
+ onCancel,
191
+ };
192
+ },
193
+ };
194
+ // 操作列编辑态改成保存、取消按钮
195
+ if (isActions) {
196
+ resCol.render = (record, index) => {
197
+ // 编辑态操作栏变成保存和取消按钮
198
+ if (editMode === "line" && record[idKey] === editingId) {
199
+ return (
200
+ <div className="edit-table-actions">
201
+ <Button
202
+ type="link"
203
+ onClick={() => {
204
+ onEditSave({ field: undefined, dataIndex: undefined, id: record[idKey] });
205
+ }}
206
+ >
207
+ 保存
208
+ </Button>
209
+ <Button type="text" onClick={onCancel}>
210
+ 取消
211
+ </Button>
212
+ </div>
213
+ );
214
+ }
215
+ return col.render(record, index);
216
+ };
217
+ }
218
+ return resCol;
219
+ });
220
+
221
+ return {
222
+ onEditAFetch,
223
+ onEdit,
224
+ onEditSave,
225
+ onEditCancel: onCancel,
226
+ SchemaField,
227
+ mergedColumns,
228
+ };
229
+ };
@@ -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-line-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,266 @@
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
+ option = {};
15
+ constructor(params) {
16
+ const { schema, option } = params || {};
17
+ this._schema = cloneDeep(schema);
18
+ this.option = option || {};
19
+ }
20
+ /**
21
+ * 处理 schema,把普通的 schema 表单字段转为自增表格的列
22
+ * @returns
23
+ */
24
+ handleSchema(schema = this._schema, opt?) {
25
+ const { isDargTable, hasAction } = opt || this.option;
26
+ const schemaTpl = this.getSchemaTpl();
27
+ const properties: Record<string, any> = {};
28
+ // schema 布局信息
29
+ schemaTpl.form = {
30
+ ...schema.form,
31
+ };
32
+
33
+ // 添加拖拽排序列
34
+ isDargTable && this.pushItem(properties, this.getSortTpl());
35
+ // 添加序号
36
+ isDargTable && this.pushItem(properties, this.getIndexTpl());
37
+ // 处理表单数据列
38
+ Object.keys(schema.schema?.properties).forEach((key, i) => {
39
+ const it = schema.schema?.properties[key];
40
+ // @ts-ignore
41
+ if (it.inTable === false) {
42
+ return;
43
+ }
44
+ this.pushItem(properties, this.handleCol(it));
45
+ });
46
+ // 添加操作列
47
+ hasAction !== false && this.pushItem(properties, this.getActionsTpl());
48
+ // 添加移动排序操作列
49
+ isDargTable && this.pushItem(properties, this.getMoveActionsTpl());
50
+
51
+ schemaTpl.schema.properties.arrayTable.items.properties = properties;
52
+ console.log("schemaTpl", schemaTpl);
53
+
54
+ return schemaTpl;
55
+ }
56
+ /**
57
+ * 处理列的数据
58
+ * @param {*} item
59
+ * @param {*} idx
60
+ * @returns
61
+ */
62
+ handleCol(item, idx = 0) {
63
+ const id = `${item.name}-${nanoidNumALetters()}`;
64
+ const _item = cloneDeep(item);
65
+ _item.title = "";
66
+ return {
67
+ type: "void",
68
+ "x-component": "ArrayTable.Column",
69
+ "x-component-props": {
70
+ title: item.title,
71
+ },
72
+ "x-designable-id": id,
73
+ name: id,
74
+ "x-index": idx,
75
+ properties: {
76
+ [item.name]: _item,
77
+ },
78
+ };
79
+ }
80
+ /**
81
+ * 在 properties 中指定序号添加一项
82
+ * @param {*} properties
83
+ * @param {*} item
84
+ * @param {*} idx
85
+ */
86
+ addItem(properties, item, idx) {
87
+ // 数组存放实际顺序
88
+ const arr = [];
89
+ // 获取当前排序的数组
90
+ Object.keys(properties).forEach((key) => {
91
+ const it = properties[key];
92
+ arr[it["x-index"]] = it;
93
+ });
94
+ // 在指定位置添加项
95
+ arr.splice(idx, 0, item);
96
+ // 根据数组顺序更新源数据
97
+ arr.forEach((it) => {
98
+ properties[it.name] = it;
99
+ });
100
+ return properties;
101
+ }
102
+ /**
103
+ * 在 properties 中添加一项
104
+ * @param {*} properties
105
+ * @param {*} item
106
+ */
107
+ pushItem(properties, item) {
108
+ properties[item.name] = cloneDeep(item);
109
+ properties[item.name]["x-index"] = Object.keys(properties).length - 1;
110
+ return properties;
111
+ }
112
+ sortItems() {}
113
+ /**
114
+ * 获取 schema 模板字符串
115
+ * @returns
116
+ */
117
+ getSchemaTpl() {
118
+ return {
119
+ form: {},
120
+ schema: {
121
+ type: "object",
122
+ properties: {
123
+ arrayTable: {
124
+ type: "array",
125
+ "x-decorator": "FormItem",
126
+ "x-component": "ArrayTable",
127
+ "x-validator": [],
128
+ "x-component-props": {
129
+ pagination: false,
130
+ onSortStart() {
131
+ console.log("onSortStart");
132
+ },
133
+ onSortEnd() {
134
+ console.log("onSortEnd");
135
+ },
136
+ },
137
+ "x-decorator-props": {},
138
+ "x-designable-id": "arrayTable",
139
+ "x-index": 0,
140
+ items: {
141
+ type: "object",
142
+ "x-designable-id": "gbmerqeme8g",
143
+ properties: {
144
+ // 自增表格列
145
+ },
146
+ },
147
+ // 新增按钮
148
+ properties: {
149
+ // cs1marpxdon: {
150
+ // type: "void",
151
+ // title: "Addition",
152
+ // "x-component": "ArrayTable.Addition",
153
+ // "x-designable-id": "cs1marpxdon",
154
+ // "x-index": 0,
155
+ // },
156
+ },
157
+ },
158
+ },
159
+ "x-designable-id": "un3pxnx4ong",
160
+ },
161
+ };
162
+ }
163
+ /**
164
+ * 获取排序列模板字符串
165
+ * @returns
166
+ */
167
+ getSortTpl() {
168
+ return {
169
+ name: "sort",
170
+ type: "void",
171
+ "x-component": "ArrayTable.Column",
172
+ "x-component-props": {
173
+ title: "",
174
+ },
175
+ "x-designable-id": "l3z7t4ff7zw",
176
+ "x-index": 0,
177
+ properties: {
178
+ g0cxfnsnevh: {
179
+ type: "void",
180
+ "x-component": "ArrayTable.SortHandle",
181
+ "x-designable-id": "g0cxfnsnevh",
182
+ "x-index": 0,
183
+ },
184
+ },
185
+ };
186
+ }
187
+ getIndexTpl() {
188
+ return {
189
+ name: "index",
190
+ type: "void",
191
+ "x-component": "ArrayTable.Column",
192
+ "x-component-props": {
193
+ title: "序号",
194
+ },
195
+ "x-designable-id": "4ps6b3ut7ft",
196
+ properties: {
197
+ TableIndex: {
198
+ type: "void",
199
+ "x-component": "TableIndex",
200
+ "x-designable-id": "TableIndex",
201
+ "x-index": 0,
202
+ },
203
+ },
204
+ };
205
+ }
206
+ /**
207
+ * 获取操作列模板字符串
208
+ * @returns
209
+ */
210
+ getActionsTpl() {
211
+ return {
212
+ name: "actions",
213
+ type: "void",
214
+ "x-component": "ArrayTable.Column",
215
+ "x-component-props": {
216
+ title: "操作",
217
+ },
218
+ "x-designable-id": "actions",
219
+ properties: {
220
+ tableActions: {
221
+ type: "void",
222
+ "x-component": "TableActions",
223
+ "x-designable-id": "tableActions",
224
+ "x-index": 0,
225
+ },
226
+ },
227
+ };
228
+ }
229
+ /**
230
+ * 获取移动排序操作列模板字符串
231
+ * @returns
232
+ */
233
+ getMoveActionsTpl() {
234
+ return {
235
+ name: "move-actions",
236
+ type: "void",
237
+ "x-component": "ArrayTable.Column",
238
+ "x-component-props": {
239
+ title: "",
240
+ },
241
+ "x-designable-id": "move-actions",
242
+ properties: {
243
+ xynjkn08lvp: {
244
+ type: "void",
245
+ "x-component": "ArrayTable.Remove",
246
+ "x-designable-id": "xynjkn08lvp",
247
+ "x-index": 0,
248
+ },
249
+ gvl20uo8m8q: {
250
+ type: "void",
251
+ "x-component": "ArrayTable.MoveDown",
252
+ "x-designable-id": "gvl20uo8m8q",
253
+ "x-index": 1,
254
+ },
255
+ "4c8wbndejhy": {
256
+ type: "void",
257
+ "x-component": "ArrayTable.MoveUp",
258
+ "x-designable-id": "4c8wbndejhy",
259
+ "x-index": 2,
260
+ },
261
+ },
262
+ };
263
+ }
264
+ }
265
+
266
+ export default SchemaToArrayTable;
@@ -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