@hzab/list-render 1.10.15 → 1.10.17-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,260 @@
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
+ },
131
+ "x-decorator-props": {},
132
+ "x-designable-id": "arrayTable",
133
+ "x-index": 0,
134
+ items: {
135
+ type: "object",
136
+ "x-designable-id": "gbmerqeme8g",
137
+ properties: {
138
+ // 自增表格列
139
+ },
140
+ },
141
+ // 新增按钮
142
+ properties: {
143
+ // cs1marpxdon: {
144
+ // type: "void",
145
+ // title: "Addition",
146
+ // "x-component": "ArrayTable.Addition",
147
+ // "x-designable-id": "cs1marpxdon",
148
+ // "x-index": 0,
149
+ // },
150
+ },
151
+ },
152
+ },
153
+ "x-designable-id": "un3pxnx4ong",
154
+ },
155
+ };
156
+ }
157
+ /**
158
+ * 获取排序列模板字符串
159
+ * @returns
160
+ */
161
+ getSortTpl() {
162
+ return {
163
+ name: "sort",
164
+ type: "void",
165
+ "x-component": "ArrayTable.Column",
166
+ "x-component-props": {
167
+ title: "",
168
+ },
169
+ "x-designable-id": "l3z7t4ff7zw",
170
+ "x-index": 0,
171
+ properties: {
172
+ g0cxfnsnevh: {
173
+ type: "void",
174
+ "x-component": "ArrayTable.SortHandle",
175
+ "x-designable-id": "g0cxfnsnevh",
176
+ "x-index": 0,
177
+ },
178
+ },
179
+ };
180
+ }
181
+ getIndexTpl() {
182
+ return {
183
+ name: "index",
184
+ type: "void",
185
+ "x-component": "ArrayTable.Column",
186
+ "x-component-props": {
187
+ title: "序号",
188
+ },
189
+ "x-designable-id": "4ps6b3ut7ft",
190
+ properties: {
191
+ TableIndex: {
192
+ type: "void",
193
+ "x-component": "TableIndex",
194
+ "x-designable-id": "TableIndex",
195
+ "x-index": 0,
196
+ },
197
+ },
198
+ };
199
+ }
200
+ /**
201
+ * 获取操作列模板字符串
202
+ * @returns
203
+ */
204
+ getActionsTpl() {
205
+ return {
206
+ name: "actions",
207
+ type: "void",
208
+ "x-component": "ArrayTable.Column",
209
+ "x-component-props": {
210
+ title: "操作",
211
+ },
212
+ "x-designable-id": "actions",
213
+ properties: {
214
+ tableActions: {
215
+ type: "void",
216
+ "x-component": "TableActions",
217
+ "x-designable-id": "tableActions",
218
+ "x-index": 0,
219
+ },
220
+ },
221
+ };
222
+ }
223
+ /**
224
+ * 获取移动排序操作列模板字符串
225
+ * @returns
226
+ */
227
+ getMoveActionsTpl() {
228
+ return {
229
+ name: "move-actions",
230
+ type: "void",
231
+ "x-component": "ArrayTable.Column",
232
+ "x-component-props": {
233
+ title: "",
234
+ },
235
+ "x-designable-id": "move-actions",
236
+ properties: {
237
+ xynjkn08lvp: {
238
+ type: "void",
239
+ "x-component": "ArrayTable.Remove",
240
+ "x-designable-id": "xynjkn08lvp",
241
+ "x-index": 0,
242
+ },
243
+ gvl20uo8m8q: {
244
+ type: "void",
245
+ "x-component": "ArrayTable.MoveDown",
246
+ "x-designable-id": "gvl20uo8m8q",
247
+ "x-index": 1,
248
+ },
249
+ "4c8wbndejhy": {
250
+ type: "void",
251
+ "x-component": "ArrayTable.MoveUp",
252
+ "x-designable-id": "4c8wbndejhy",
253
+ "x-index": 2,
254
+ },
255
+ },
256
+ };
257
+ }
258
+ }
259
+
260
+ export default SchemaToArrayTable;
@@ -10,6 +10,7 @@ import axios, { getCancelTokenSource } from "@hzab/data-model/src/axios";
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";
@@ -193,6 +194,7 @@ const ListRender = forwardRef(function (props, parentRef) {
193
194
  setTotal(res.pagination?.total);
194
195
  props.onGetListEnd && props.onGetListEnd(res);
195
196
  setListLoading(false);
197
+ return res;
196
198
  })
197
199
  .catch((err) => {
198
200
  if (axios.isCancel(err)) {
@@ -384,7 +386,7 @@ const ListRender = forwardRef(function (props, parentRef) {
384
386
  async function onEditSubmit(data, opt) {
385
387
  let _data = data;
386
388
  if (isPatchUpdate) {
387
- if (model?.patchMap === "function") {
389
+ if (typeof model?.patchMap === "function") {
388
390
  _data = model.patchMap(data, opt);
389
391
  }
390
392
  } else if (typeof model?.updateMap === "function") {
@@ -440,6 +442,9 @@ const ListRender = forwardRef(function (props, parentRef) {
440
442
  setShowSearch(!showSearch);
441
443
  };
442
444
 
445
+ const CTableRender =
446
+ props.editMode === "table-edit" || props.editMode === "table-edit-show" ? EditArrayTable : TableRender;
447
+
443
448
  return (
444
449
  <div className={`list-render ${props.className}`}>
445
450
  <div className={`list-header ${props.verticalHeader ? "vertical-header" : ""}`}>
@@ -502,10 +507,10 @@ const ListRender = forwardRef(function (props, parentRef) {
502
507
  ) : null}
503
508
 
504
509
  {layout === "default" ? (
505
- <TableRender
510
+ <CTableRender
506
511
  idKey={idKey}
507
512
  ref={tableRef}
508
- schema={schema?.schema}
513
+ schema={schema}
509
514
  list={list}
510
515
  config={props.tableConf}
511
516
  hasAction={props.hasAction}
@@ -526,6 +531,7 @@ const ListRender = forwardRef(function (props, parentRef) {
526
531
  i18n={i18n}
527
532
  onEditSubmit={onEditSubmit}
528
533
  topProps={props}
534
+ handleMessage={handleMessage}
529
535
  />
530
536
  ) : null}
531
537
 
@@ -1,51 +1,51 @@
1
- import { useEffect, useState } from "react";
2
- import { Pagination } from "antd";
3
-
4
- import "./index.less";
5
-
6
- function PaginationRender(props) {
7
- const [pageSize, setPageSize] = useState(props.query?.pageSize || pageSizeOptions[0]);
8
- const [pageNum, setPageNumber] = useState(props.query?.pageNum || 1);
9
-
10
- useEffect(() => {
11
- const { query } = props;
12
- if (!query) {
13
- return;
14
- }
15
- if (query.pageSize && query.pageSize !== pageSize) {
16
- setPageSize(query.pageSize);
17
- }
18
- if (query.pageNum && query.pageNum !== pageNum) {
19
- setPageNumber(query.pageNum);
20
- }
21
- }, [props.query?.pageNum, props.query?.pageSize]);
22
-
23
- function onChange(page, size) {
24
- let _size = size;
25
- let _page = page;
26
- if (pageSize !== size) {
27
- _page = 1;
28
- }
29
- setPageSize(_size);
30
- setPageNumber(_page);
31
- props.onChange && props.onChange(_page, _size);
32
- }
33
-
34
- return (
35
- <div className="pagination-render-wrap">
36
- <Pagination
37
- {...(props.config || {})}
38
- className="pagination-render"
39
- current={pageNum}
40
- pageSize={pageSize}
41
- onChange={onChange}
42
- pageSizeOptions={props.pageSizeOptions}
43
- total={props.total}
44
- showTotal={(total) => `总条数 ${total} 条`}
45
- showSizeChanger
46
- />
47
- </div>
48
- );
49
- }
50
-
51
- export default PaginationRender;
1
+ import { useEffect, useState } from "react";
2
+ import { Pagination } from "antd";
3
+
4
+ import "./index.less";
5
+
6
+ function PaginationRender(props) {
7
+ const [pageSize, setPageSize] = useState(props.query?.pageSize || pageSizeOptions[0]);
8
+ const [pageNum, setPageNumber] = useState(props.query?.pageNum || 1);
9
+
10
+ useEffect(() => {
11
+ const { query } = props;
12
+ if (!query) {
13
+ return;
14
+ }
15
+ if (query.pageSize && query.pageSize !== pageSize) {
16
+ setPageSize(query.pageSize);
17
+ }
18
+ if (query.pageNum && query.pageNum !== pageNum) {
19
+ setPageNumber(query.pageNum);
20
+ }
21
+ }, [props.query?.pageNum, props.query?.pageSize]);
22
+
23
+ function onChange(page, size) {
24
+ let _size = size;
25
+ let _page = page;
26
+ if (pageSize !== size) {
27
+ _page = 1;
28
+ }
29
+ setPageSize(_size);
30
+ setPageNumber(_page);
31
+ props.onChange && props.onChange(_page, _size);
32
+ }
33
+
34
+ return (
35
+ <div className="pagination-render-wrap">
36
+ <Pagination
37
+ {...(props.config || {})}
38
+ className="pagination-render"
39
+ current={pageNum}
40
+ pageSize={pageSize}
41
+ onChange={onChange}
42
+ pageSizeOptions={props.pageSizeOptions}
43
+ total={props.total}
44
+ showTotal={(total) => `总条数 ${total} 条`}
45
+ showSizeChanger
46
+ />
47
+ </div>
48
+ );
49
+ }
50
+
51
+ export default PaginationRender;