@hzab/form-render 1.4.0 → 1.5.0-beta

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,151 @@
1
+ import React from "react";
2
+ import { Card, Empty } from "antd";
3
+ import { CardProps } from "antd/lib/card";
4
+ import { ArrayField } from "@formily/core";
5
+ import { useField, observer, useFieldSchema, RecursionField } from "@formily/react";
6
+ import cls from "classnames";
7
+ import { ISchema } from "@formily/json-schema";
8
+ import { usePrefixCls } from "c-formily-antd/lib/__builtins__";
9
+ import { ArrayBase, ArrayBaseMixins, IArrayBaseProps } from "../ArrayBase";
10
+
11
+ type ComposedArrayCards = React.FC<React.PropsWithChildren<CardProps & IArrayBaseProps>> & ArrayBaseMixins;
12
+
13
+ const isAdditionComponent = (schema: ISchema) => {
14
+ return schema["x-component"]?.indexOf("Addition") > -1;
15
+ };
16
+
17
+ const isIndexComponent = (schema: ISchema) => {
18
+ return schema["x-component"]?.indexOf?.("Index") > -1;
19
+ };
20
+
21
+ const isRemoveComponent = (schema: ISchema) => {
22
+ return schema["x-component"]?.indexOf?.("Remove") > -1;
23
+ };
24
+
25
+ const isCopyComponent = (schema: ISchema) => {
26
+ return schema["x-component"]?.indexOf?.("Copy") > -1;
27
+ };
28
+
29
+ const isMoveUpComponent = (schema: ISchema) => {
30
+ return schema["x-component"]?.indexOf?.("MoveUp") > -1;
31
+ };
32
+
33
+ const isMoveDownComponent = (schema: ISchema) => {
34
+ return schema["x-component"]?.indexOf?.("MoveDown") > -1;
35
+ };
36
+
37
+ const isOperationComponent = (schema: ISchema) => {
38
+ return (
39
+ isAdditionComponent(schema) ||
40
+ isRemoveComponent(schema) ||
41
+ isCopyComponent(schema) ||
42
+ isMoveDownComponent(schema) ||
43
+ isMoveUpComponent(schema)
44
+ );
45
+ };
46
+
47
+ export const ArrayCards: ComposedArrayCards = observer((props) => {
48
+ const field = useField<ArrayField>();
49
+ const schema = useFieldSchema();
50
+ const dataSource = Array.isArray(field.value) ? field.value : [];
51
+ const prefixCls = usePrefixCls("formily-array-cards", props);
52
+ const { onAdd, onCopy, onRemove, onMoveDown, onMoveUp, ...cardProps } = props;
53
+
54
+ if (!schema) throw new Error("can not found schema object");
55
+
56
+ const renderItems = () => {
57
+ return dataSource?.map((item, index) => {
58
+ const items = Array.isArray(schema.items) ? schema.items[index] || schema.items[0] : schema.items;
59
+ const title = (
60
+ <span>
61
+ <RecursionField
62
+ schema={items}
63
+ name={index}
64
+ filterProperties={(schema) => {
65
+ if (!isIndexComponent(schema)) return false;
66
+ return true;
67
+ }}
68
+ onlyRenderProperties
69
+ />
70
+ {props.title || field.title}
71
+ </span>
72
+ );
73
+ const extra = (
74
+ <span>
75
+ <RecursionField
76
+ schema={items}
77
+ name={index}
78
+ filterProperties={(schema) => {
79
+ if (!isOperationComponent(schema)) return false;
80
+ return true;
81
+ }}
82
+ onlyRenderProperties
83
+ />
84
+ {props.extra}
85
+ </span>
86
+ );
87
+ const content = (
88
+ <RecursionField
89
+ schema={items}
90
+ name={index}
91
+ filterProperties={(schema) => {
92
+ if (isIndexComponent(schema)) return false;
93
+ if (isOperationComponent(schema)) return false;
94
+ return true;
95
+ }}
96
+ />
97
+ );
98
+ return (
99
+ // ! key 用于排序,必须是序号
100
+ <ArrayBase.Item key={index} index={index} record={() => field.value?.[index]}>
101
+ <Card
102
+ {...cardProps}
103
+ onChange={() => {}}
104
+ className={cls(`${prefixCls}-item`, props.className)}
105
+ title={title}
106
+ extra={extra}
107
+ >
108
+ {content}
109
+ </Card>
110
+ </ArrayBase.Item>
111
+ );
112
+ });
113
+ };
114
+
115
+ const renderAddition = () => {
116
+ return schema.reduceProperties((addition, schema, key) => {
117
+ if (isAdditionComponent(schema)) {
118
+ return <RecursionField schema={schema} name={key} />;
119
+ }
120
+ return addition;
121
+ }, null);
122
+ };
123
+
124
+ const renderEmpty = () => {
125
+ if (dataSource?.length) return;
126
+ return (
127
+ <Card
128
+ {...cardProps}
129
+ onChange={() => {}}
130
+ className={cls(`${prefixCls}-item`, props.className)}
131
+ title={props.title || field.title}
132
+ >
133
+ <Empty />
134
+ </Card>
135
+ );
136
+ };
137
+
138
+ return (
139
+ <ArrayBase onAdd={onAdd} onCopy={onCopy} onRemove={onRemove} onMoveUp={onMoveUp} onMoveDown={onMoveDown}>
140
+ {renderEmpty()}
141
+ {renderItems()}
142
+ {renderAddition()}
143
+ </ArrayBase>
144
+ );
145
+ });
146
+
147
+ ArrayCards.displayName = "ArrayCards";
148
+
149
+ ArrayBase.mixin(ArrayCards);
150
+
151
+ export default ArrayCards;
@@ -0,0 +1,15 @@
1
+ @root-entry-name: 'default';
2
+ @import (reference) '~antd/es/style/themes/index.less';
3
+
4
+ @array-base-prefix-cls: ~'@{ant-prefix}-formily-array-base';
5
+ @array-cards-prefix-cls: ~'@{ant-prefix}-formily-array-cards';
6
+
7
+ .@{array-cards-prefix-cls}-item {
8
+ margin-bottom: 10px !important;
9
+ }
10
+
11
+ .ant-card-extra {
12
+ .@{array-base-prefix-cls}-copy {
13
+ margin-left: 6px;
14
+ }
15
+ }
@@ -0,0 +1,4 @@
1
+ import 'antd/lib/card/style/index'
2
+ import 'antd/lib/empty/style/index'
3
+ import 'antd/lib/button/style/index'
4
+ import './style.less'
@@ -0,0 +1,405 @@
1
+ import React, { Fragment, useState, useRef, useEffect, createContext, useContext, useCallback } from "react";
2
+ import { Table, Pagination, Space, Select, Badge } from "antd";
3
+ import { PaginationProps } from "antd/lib/pagination";
4
+ import { TableProps, ColumnProps } from "antd/lib/table";
5
+ import { SelectProps } from "antd/lib/select";
6
+ import cls from "classnames";
7
+ import { GeneralField, FieldDisplayTypes, ArrayField } from "@formily/core";
8
+ import { useField, observer, useFieldSchema, RecursionField, ReactFC } from "@formily/react";
9
+ import { isArr, isBool, isFn } from "@formily/shared";
10
+ import { Schema } from "@formily/json-schema";
11
+ import { usePrefixCls, SortableContainer, SortableElement } from "c-formily-antd/lib/__builtins__";
12
+ import { ArrayBase, ArrayBaseMixins, IArrayBaseProps } from "../ArrayBase";
13
+
14
+ interface ObservableColumnSource {
15
+ field: GeneralField;
16
+ columnProps: ColumnProps<any>;
17
+ schema: Schema;
18
+ display: FieldDisplayTypes;
19
+ name: string;
20
+ }
21
+ interface IArrayTablePaginationProps extends PaginationProps {
22
+ dataSource?: any[];
23
+ showPagination?: boolean;
24
+ children?: (
25
+ dataSource: any[],
26
+ pagination: React.ReactNode,
27
+ options: {
28
+ startIndex: number;
29
+ },
30
+ ) => React.ReactElement;
31
+ }
32
+
33
+ interface IStatusSelectProps extends SelectProps<any> {
34
+ pageSize?: number;
35
+ }
36
+
37
+ type ComposedArrayTable = React.FC<React.PropsWithChildren<TableProps<any> & IArrayBaseProps>> &
38
+ ArrayBaseMixins & {
39
+ Column?: React.FC<React.PropsWithChildren<ColumnProps<any>>>;
40
+ };
41
+
42
+ interface PaginationAction {
43
+ totalPage?: number;
44
+ pageSize?: number;
45
+ showPagination?: boolean;
46
+ changePage?: (page: number) => void;
47
+ }
48
+
49
+ const SortableRow = SortableElement((props: any) => <tr {...props} />);
50
+ const SortableBody = SortableContainer((props: any) => <tbody {...props} />);
51
+
52
+ const isColumnComponent = (schema: Schema) => {
53
+ return schema["x-component"]?.indexOf("Column") > -1;
54
+ };
55
+
56
+ const isOperationsComponent = (schema: Schema) => {
57
+ return schema["x-component"]?.indexOf("Operations") > -1;
58
+ };
59
+
60
+ const isAdditionComponent = (schema: Schema) => {
61
+ return schema["x-component"]?.indexOf("Addition") > -1;
62
+ };
63
+
64
+ const useArrayTableSources = () => {
65
+ const arrayField = useField();
66
+ const schema = useFieldSchema();
67
+ const parseSources = (schema: Schema): ObservableColumnSource[] => {
68
+ if (isColumnComponent(schema) || isOperationsComponent(schema) || isAdditionComponent(schema)) {
69
+ if (!schema["x-component-props"]?.["dataIndex"] && !schema["name"]) return [];
70
+ const name = schema["x-component-props"]?.["dataIndex"] || schema["name"];
71
+ const field = arrayField.query(arrayField.address.concat(name)).take();
72
+ const columnProps = field?.component?.[1] || schema["x-component-props"] || {};
73
+ const display = field?.display || schema["x-display"] || "visible";
74
+ return [
75
+ {
76
+ name,
77
+ display,
78
+ field,
79
+ schema,
80
+ columnProps,
81
+ },
82
+ ];
83
+ } else if (schema.properties) {
84
+ return schema.reduceProperties((buf, schema) => {
85
+ return buf.concat(parseSources(schema));
86
+ }, []);
87
+ }
88
+ };
89
+
90
+ const parseArrayItems = (schema: Schema["items"]) => {
91
+ if (!schema) return [];
92
+ const sources: ObservableColumnSource[] = [];
93
+ const items = isArr(schema) ? schema : [schema];
94
+ return items.reduce((columns, schema) => {
95
+ const item = parseSources(schema);
96
+ if (item) {
97
+ return columns.concat(item);
98
+ }
99
+ return columns;
100
+ }, sources);
101
+ };
102
+
103
+ if (!schema) throw new Error("can not found schema object");
104
+
105
+ return parseArrayItems(schema.items);
106
+ };
107
+
108
+ const useArrayTableColumns = (
109
+ dataSource: any[],
110
+ field: ArrayField,
111
+ sources: ObservableColumnSource[],
112
+ ): TableProps<any>["columns"] => {
113
+ return sources.reduce((buf, { name, columnProps, schema, display }, key) => {
114
+ if (display !== "visible") return buf;
115
+ if (!isColumnComponent(schema)) return buf;
116
+ return buf.concat({
117
+ ...columnProps,
118
+ // ! key 用于排序,必须是序号
119
+ key,
120
+ dataIndex: name,
121
+ render: (value: any, record: any) => {
122
+ const index = dataSource?.indexOf(record);
123
+ const children = (
124
+ <ArrayBase.Item index={index} record={() => field?.value?.[index]}>
125
+ <RecursionField schema={schema} name={index} onlyRenderProperties />
126
+ </ArrayBase.Item>
127
+ );
128
+ return children;
129
+ },
130
+ });
131
+ }, []);
132
+ };
133
+
134
+ const useAddition = () => {
135
+ const schema = useFieldSchema();
136
+ return schema.reduceProperties((addition, schema, key) => {
137
+ if (isAdditionComponent(schema)) {
138
+ return <RecursionField schema={schema} name={key} />;
139
+ }
140
+ return addition;
141
+ }, null);
142
+ };
143
+
144
+ const schedulerRequest = {
145
+ request: null,
146
+ };
147
+
148
+ const StatusSelect: ReactFC<IStatusSelectProps> = observer(
149
+ (props) => {
150
+ const field = useField<ArrayField>();
151
+ const prefixCls = usePrefixCls("formily-array-table");
152
+ const errors = field.errors;
153
+ const parseIndex = (address: string) => {
154
+ return Number(address.slice(address.indexOf(field.address.toString()) + 1).match(/(\d+)/)?.[1]);
155
+ };
156
+ const options = props.options?.map(({ label, value }) => {
157
+ const val = Number(value);
158
+ const hasError = errors.some(({ address }) => {
159
+ const currentIndex = parseIndex(address);
160
+ const startIndex = (val - 1) * props.pageSize;
161
+ const endIndex = val * props.pageSize;
162
+ return currentIndex >= startIndex && currentIndex <= endIndex;
163
+ });
164
+ return {
165
+ label: hasError ? <Badge dot>{label}</Badge> : label,
166
+ value,
167
+ };
168
+ });
169
+
170
+ const width = String(options?.length).length * 15;
171
+
172
+ return (
173
+ <Select
174
+ value={props.value}
175
+ onChange={props.onChange}
176
+ options={options}
177
+ virtual
178
+ style={{
179
+ width: width < 60 ? 60 : width,
180
+ }}
181
+ className={cls(`${prefixCls}-status-select`, {
182
+ "has-error": errors?.length,
183
+ })}
184
+ />
185
+ );
186
+ },
187
+ {
188
+ scheduler: (update) => {
189
+ clearTimeout(schedulerRequest.request);
190
+ schedulerRequest.request = setTimeout(() => {
191
+ update();
192
+ }, 100);
193
+ },
194
+ },
195
+ );
196
+
197
+ const PaginationContext = createContext<PaginationAction>({});
198
+ const usePagination = () => {
199
+ return useContext(PaginationContext);
200
+ };
201
+
202
+ const ArrayTablePagination: ReactFC<IArrayTablePaginationProps> = (props) => {
203
+ const [current, setCurrent] = useState(1);
204
+ const prefixCls = usePrefixCls("formily-array-table");
205
+ const showPagination = props.showPagination ?? true;
206
+ const pageSize = props.pageSize || 10;
207
+ const size = props.size || "default";
208
+ const dataSource = props.dataSource || [];
209
+ const startIndex = (current - 1) * pageSize;
210
+ const endIndex = startIndex + pageSize - 1;
211
+ const total = dataSource?.length || 0;
212
+ const totalPage = Math.ceil(total / pageSize);
213
+ const pages = Array.from(new Array(totalPage)).map((_, index) => {
214
+ const page = index + 1;
215
+ return {
216
+ label: page,
217
+ value: page,
218
+ };
219
+ });
220
+ const handleChange = (current: number) => {
221
+ setCurrent(current);
222
+ };
223
+
224
+ useEffect(() => {
225
+ if (totalPage > 0 && totalPage < current) {
226
+ handleChange(totalPage);
227
+ }
228
+ }, [totalPage, current]);
229
+
230
+ const renderPagination = () => {
231
+ if (totalPage <= 1 || !showPagination) return;
232
+ return (
233
+ <div className={`${prefixCls}-pagination`}>
234
+ <Space>
235
+ <StatusSelect
236
+ value={current}
237
+ pageSize={pageSize}
238
+ onChange={handleChange}
239
+ options={pages}
240
+ notFoundContent={false}
241
+ />
242
+ <Pagination
243
+ {...props}
244
+ pageSize={pageSize}
245
+ current={current}
246
+ total={dataSource.length}
247
+ size={size}
248
+ showSizeChanger={false}
249
+ onChange={handleChange}
250
+ />
251
+ </Space>
252
+ </div>
253
+ );
254
+ };
255
+
256
+ return (
257
+ <Fragment>
258
+ <PaginationContext.Provider
259
+ value={{
260
+ totalPage,
261
+ pageSize,
262
+ changePage: handleChange,
263
+ showPagination,
264
+ }}
265
+ >
266
+ {props.children?.(
267
+ showPagination ? dataSource?.slice(startIndex, endIndex + 1) : dataSource,
268
+ renderPagination(),
269
+ { startIndex },
270
+ )}
271
+ </PaginationContext.Provider>
272
+ </Fragment>
273
+ );
274
+ };
275
+
276
+ const RowComp: ReactFC<React.HTMLAttributes<HTMLTableRowElement>> = (props) => {
277
+ const prefixCls = usePrefixCls("formily-array-table");
278
+ const index = props["data-row-key"] || 0;
279
+ return (
280
+ <SortableRow
281
+ lockAxis="y"
282
+ {...props}
283
+ index={index}
284
+ className={cls(props.className, `${prefixCls}-row-${index + 1}`)}
285
+ />
286
+ );
287
+ };
288
+
289
+ export const ArrayTable: ComposedArrayTable = observer((props) => {
290
+ const ref = useRef<HTMLDivElement>();
291
+ const field = useField<ArrayField>();
292
+ const prefixCls = usePrefixCls("formily-array-table");
293
+ const dataSource = Array.isArray(field.value) ? field.value.slice() : [];
294
+ const sources = useArrayTableSources();
295
+ const columns = useArrayTableColumns(dataSource, field, sources);
296
+ const pagination = isBool(props.pagination) ? { showPagination: props.pagination } : props.pagination;
297
+ const addition = useAddition();
298
+ const { onAdd, onCopy, onRemove, onMoveDown, onMoveUp } = props;
299
+ const defaultRowKey = (record: any) => {
300
+ return dataSource.indexOf(record);
301
+ };
302
+ const addTdStyles = (id: number) => {
303
+ const node = ref.current?.querySelector(`.${prefixCls}-row-${id}`);
304
+ const helper = document.body.querySelector(`.${prefixCls}-sort-helper`);
305
+ if (!helper) return;
306
+ const tds = node?.querySelectorAll("td");
307
+ if (!tds) return;
308
+ requestAnimationFrame(() => {
309
+ helper.querySelectorAll("td").forEach((td, index) => {
310
+ if (tds[index]) {
311
+ td.style.width = getComputedStyle(tds[index]).width;
312
+ }
313
+ });
314
+ });
315
+ };
316
+ const getWrapperComp = useCallback(
317
+ (dataSource: any[], start: number) => (props: any) =>
318
+ (
319
+ <SortableBody
320
+ {...props}
321
+ start={start}
322
+ list={dataSource.slice()}
323
+ accessibility={{
324
+ container: ref.current || undefined,
325
+ }}
326
+ onSortStart={(event) => {
327
+ addTdStyles(event.active.id as number);
328
+ }}
329
+ onSortEnd={({ oldIndex, newIndex }) => {
330
+ field.move(oldIndex, newIndex);
331
+ }}
332
+ className={cls(`${prefixCls}-sort-helper`, props.className)}
333
+ />
334
+ ),
335
+ [field],
336
+ );
337
+ return (
338
+ <ArrayTablePagination {...pagination} dataSource={dataSource}>
339
+ {(dataSource, pager, { startIndex }) => (
340
+ <div ref={ref} className={prefixCls}>
341
+ <ArrayBase onAdd={onAdd} onCopy={onCopy} onRemove={onRemove} onMoveUp={onMoveUp} onMoveDown={onMoveDown}>
342
+ <Table
343
+ size="small"
344
+ bordered
345
+ rowKey={defaultRowKey}
346
+ {...props}
347
+ onChange={() => {}}
348
+ pagination={false}
349
+ columns={columns}
350
+ dataSource={dataSource}
351
+ components={{
352
+ body: {
353
+ wrapper: getWrapperComp(dataSource, startIndex),
354
+ row: RowComp,
355
+ },
356
+ }}
357
+ />
358
+ <div style={{ marginTop: 5, marginBottom: 5 }}>{pager}</div>
359
+ {sources.map((column, key) => {
360
+ //专门用来承接对Column的状态管理
361
+ if (!isColumnComponent(column.schema)) return;
362
+ return React.createElement(RecursionField, {
363
+ name: column.name,
364
+ schema: column.schema,
365
+ onlyRenderSelf: true,
366
+ // ! key 用于排序,必须是序号
367
+ key,
368
+ });
369
+ })}
370
+ {addition}
371
+ </ArrayBase>
372
+ </div>
373
+ )}
374
+ </ArrayTablePagination>
375
+ );
376
+ });
377
+
378
+ ArrayTable.displayName = "ArrayTable";
379
+
380
+ ArrayTable.Column = () => {
381
+ return <Fragment />;
382
+ };
383
+
384
+ ArrayBase.mixin(ArrayTable);
385
+
386
+ const Addition: ArrayBaseMixins["Addition"] = (props) => {
387
+ const array = ArrayBase.useArray();
388
+ const { totalPage = 0, pageSize = 10, changePage, showPagination } = usePagination();
389
+ return (
390
+ <ArrayBase.Addition
391
+ {...props}
392
+ onClick={(e) => {
393
+ // 如果添加数据后将超过当前页,则自动切换到下一页
394
+ const total = array?.field?.value.length || 0;
395
+ if (showPagination && total === totalPage * pageSize + 1 && isFn(changePage)) {
396
+ changePage(totalPage + 1);
397
+ }
398
+ props.onClick?.(e);
399
+ }}
400
+ />
401
+ );
402
+ };
403
+ ArrayTable.Addition = Addition;
404
+
405
+ export default ArrayTable;
@@ -0,0 +1,53 @@
1
+ @root-entry-name: 'default';
2
+ @import (reference) '~antd/es/style/themes/index.less';
3
+
4
+ @array-table-prefix-cls: ~'@{ant-prefix}-formily-array-table';
5
+
6
+ .@{array-table-prefix-cls} {
7
+ .@{array-table-prefix-cls}-pagination {
8
+ display: flex;
9
+ justify-content: center;
10
+
11
+ .@{array-table-prefix-cls}-status-select.has-error {
12
+ .@{ant-prefix}-select-selector {
13
+ border-color: @error-color !important;
14
+ }
15
+ }
16
+ }
17
+
18
+ .@{ant-prefix}-table {
19
+ table {
20
+ overflow: hidden;
21
+ }
22
+
23
+ td {
24
+ visibility: visible;
25
+
26
+ .@{ant-prefix}-formily-item:not(.@{ant-prefix}-formily-item-feedback-layout-popover) {
27
+ margin-bottom: 0 !important;
28
+
29
+ .@{ant-prefix}-formily-item-help {
30
+ position: absolute;
31
+ font-size: 12px;
32
+ top: 100%;
33
+ background: #fff;
34
+ width: 100%;
35
+ margin-top: 3px;
36
+ padding: 3px;
37
+ z-index: 1;
38
+ border-radius: 3px;
39
+ box-shadow: 0 0 10px #eee;
40
+ animation: none;
41
+ transform: translateY(0);
42
+ opacity: 1;
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ .@{array-table-prefix-cls}-sort-helper {
49
+ background: #fff;
50
+ border: 1px solid #eee;
51
+ z-index: 10;
52
+ }
53
+ }
@@ -0,0 +1,7 @@
1
+ import 'antd/lib/table/style/index'
2
+ import 'antd/lib/button/style/index'
3
+ import 'antd/lib/select/style/index'
4
+ import 'antd/lib/space/style/index'
5
+ import 'antd/lib/badge/style/index'
6
+ import 'antd/lib/pagination/style/index'
7
+ import './style.less'
@@ -76,12 +76,11 @@ DatePicker.RangePicker = connect(
76
76
  };
77
77
 
78
78
  const handleOnChange = (dates, dateStrings) => {
79
-
80
79
  props.onChange && props.onChange(dates);
81
80
  if (!isSplitTimes) return;
82
81
  if (!dates || !dates.length) {
83
82
  handleOnConfirm(undefined, undefined);
84
- return
83
+ return;
85
84
  }
86
85
 
87
86
  const startTime = dates[0];