fix(client): required for the sub-table field

This commit is contained in:
chenos 2022-07-28 17:37:17 +08:00
parent 165ab2b876
commit 609b0e2ff2
4 changed files with 157 additions and 100 deletions

View File

@ -11,6 +11,7 @@ export const TableFieldContext = createContext<any>({});
const InternalTableFieldProvider = (props) => {
const { params = {}, showIndex, dragSort, fieldName } = props;
const field = useField();
const fieldSchema = useFieldSchema();
const { resource, service } = useBlockRequestContext();
const formBlockCtx = useFormBlockContext();
@ -28,6 +29,7 @@ const InternalTableFieldProvider = (props) => {
<TableFieldContext.Provider
value={{
field,
fieldSchema,
service,
resource,
params,
@ -151,6 +153,7 @@ export const useTableFieldProps = () => {
showIndex: ctx.showIndex,
dragSort: ctx.dragSort,
pagination: false,
required: ctx?.fieldSchema?.parent?.required,
rowKey: (record: any) => {
return field.value?.indexOf?.(record);
},

View File

@ -189,7 +189,7 @@ FormItem.Designer = (props) => {
<SchemaSettings.SwitchItem
key="required"
title={t('Required')}
checked={field.required}
checked={fieldSchema.required}
onChange={(required) => {
const schema = {
['x-uid']: fieldSchema['x-uid'],

View File

@ -1,15 +1,16 @@
import { MenuOutlined } from '@ant-design/icons';
import { SortableContext, useSortable } from '@dnd-kit/sortable';
import { css } from '@emotion/css';
import { ArrayField } from '@formily/core';
import { ArrayField, Field } from '@formily/core';
import { ISchema, observer, RecursionField, Schema, useField, useFieldSchema } from '@formily/react';
import { reaction } from '@formily/reactive';
import { useMemoizedFn } from 'ahooks';
import { Table as AntdTable, TableColumnProps } from 'antd';
import { default as classNames, default as cls } from 'classnames';
import React, { useCallback, useMemo } from 'react';
import React, { useCallback, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { DndContext } from '../..';
import { RecordIndexProvider, RecordProvider, useSchemaInitializer } from '../../../';
import { SortableContext, useSortable } from '@dnd-kit/sortable';
import { useMemoizedFn } from 'ahooks';
const isColumnComponent = (schema: Schema) => {
return schema['x-component']?.endsWith('.Column') > -1;
@ -17,7 +18,7 @@ const isColumnComponent = (schema: Schema) => {
const isCollectionFieldComponent = (schema: ISchema) => {
return schema['x-component'] === 'CollectionField';
}
};
const useTableColumns = () => {
const start = Date.now();
@ -31,12 +32,11 @@ const useTableColumns = () => {
}
}, [])
.map((s: Schema) => {
const collectionFields = s
.reduceProperties((buf, s) => {
if (isCollectionFieldComponent(s)) {
return buf.concat([s]);
}
}, []);
const collectionFields = s.reduceProperties((buf, s) => {
if (isCollectionFieldComponent(s)) {
return buf.concat([s]);
}
}, []);
const dataIndex = collectionFields?.length > 0 ? collectionFields[0].name : s.name;
return {
@ -68,34 +68,41 @@ const useTableColumns = () => {
});
};
const topActiveClass = css`
& > td {
border-top: 2px solid rgba(241, 139, 98, 0.6) !important;
}
`
`;
const bottomActiveClass = css`
& > td {
border-bottom: 2px solid rgba(241, 139, 98, 0.6) !important;
}
`
`;
const SortableRow = (props) => {
const id = props['data-row-key']?.toString()
const id = props['data-row-key']?.toString();
const { setNodeRef, isOver, active, over } = useSortable({
id
})
id,
});
const className = (active?.data.current?.sortable.index ?? -1) > (over?.data.current?.sortable.index ?? -1) ? topActiveClass : bottomActiveClass
return <tr ref={active?.id !== id ? setNodeRef : null} {...props} className={classNames({ [className]: active && isOver })} />
}
const className =
(active?.data.current?.sortable.index ?? -1) > (over?.data.current?.sortable.index ?? -1)
? topActiveClass
: bottomActiveClass;
return (
<tr
ref={active?.id !== id ? setNodeRef : null}
{...props}
className={classNames({ [className]: active && isOver })}
/>
);
};
const SortHandle = (props) => {
const { listeners } = useSortable({
id: props.id
})
id: props.id,
});
return <MenuOutlined {...listeners} style={{ cursor: 'grab' }} />;
};
@ -124,23 +131,52 @@ const usePaginationProps = (pagination1, pagination2) => {
};
};
const useValidator = (validator: (value: any) => string) => {
const field = useField<Field>();
useEffect(() => {
const dispose = reaction(
() => field.value,
(value) => {
const message = validator(value);
field.setFeedback({
type: 'error',
code: 'ValidateError',
messages: message ? [message] : [],
});
},
);
return () => {
dispose();
};
}, []);
};
export const Table: any = observer((props: any) => {
const field = useField<ArrayField>();
const columns = useTableColumns();
const { pagination: pagination1, useProps, onChange, ...others1 } = props;
const { pagination: pagination2, ...others2 } = useProps?.() || {};
const {
const columns = useTableColumns();
const { pagination: pagination1, useProps, onChange, ...others1 } = props;
const { pagination: pagination2, ...others2 } = useProps?.() || {};
const {
dragSort = false,
showIndex = true,
onRowSelectionChange,
onChange: onTableChange,
rowSelection,
rowKey,
required,
...others
} = { ...others1, ...others2 } as any;
const onRowDragEnd = useMemoizedFn(others.onRowDragEnd || (() => {}))
const onRowDragEnd = useMemoizedFn(others.onRowDragEnd || (() => {}));
const paginationProps = usePaginationProps(pagination1, pagination2);
const requiredValidator = field.required || required;
useEffect(() => {
field.setValidator((value) => {
if (requiredValidator) {
return Array.isArray(value) && value.length > 0 ? null : 'The field value is required';
}
return;
});
}, [requiredValidator]);
const components = useMemo(() => {
return {
header: {
@ -172,25 +208,27 @@ export const Table: any = observer((props: any) => {
body: {
wrapper: (props) => {
return (
<DndContext onDragEnd={(e) => {
if (!e.active || !e.over) {
console.warn('move cancel')
return
}
<DndContext
onDragEnd={(e) => {
if (!e.active || !e.over) {
console.warn('move cancel');
return;
}
const fromIndex = e.active?.data.current?.sortable?.index
const toIndex = e.over?.data.current?.sortable?.index
const from = field.value[fromIndex];
const to = field.value[toIndex];
field.move(fromIndex, toIndex);
onRowDragEnd({ fromIndex, toIndex, from, to });
}}>
const fromIndex = e.active?.data.current?.sortable?.index;
const toIndex = e.over?.data.current?.sortable?.index;
const from = field.value[fromIndex];
const to = field.value[toIndex];
field.move(fromIndex, toIndex);
onRowDragEnd({ fromIndex, toIndex, from, to });
}}
>
<tbody {...props} />
</DndContext>
);
},
row: (props) => {
return <SortableRow {...props}></SortableRow>
return <SortableRow {...props}></SortableRow>;
},
cell: (props) => (
<td
@ -209,7 +247,7 @@ export const Table: any = observer((props: any) => {
),
},
};
}, [field, onRowDragEnd, dragSort])
}, [field, onRowDragEnd, dragSort]);
const defaultRowKey = (record: any) => {
return field.value?.indexOf?.(record);
@ -219,34 +257,34 @@ export const Table: any = observer((props: any) => {
if (typeof rowKey === 'string') {
return record[rowKey]?.toString();
} else {
return (rowKey ?? defaultRowKey)(record)?.toString()
return (rowKey ?? defaultRowKey)(record)?.toString();
}
}
};
const restProps = {
rowSelection: rowSelection
? {
type: 'checkbox',
selectedRowKeys: field?.data?.selectedRowKeys || [],
onChange(selectedRowKeys: any[], selectedRows: any[]) {
field.data = field.data || {};
field.data.selectedRowKeys = selectedRowKeys;
onRowSelectionChange?.(selectedRowKeys, selectedRows);
},
renderCell: (checked, record, index, originNode) => {
if (!dragSort && !showIndex) {
return originNode;
}
const current = props?.pagination?.current;
const pageSize = props?.pagination?.pageSize || 20;
if (current) {
index = index + (current - 1) * pageSize;
}
return (
<div
className={classNames(
checked ? 'checked' : null,
css`
type: 'checkbox',
selectedRowKeys: field?.data?.selectedRowKeys || [],
onChange(selectedRowKeys: any[], selectedRows: any[]) {
field.data = field.data || {};
field.data.selectedRowKeys = selectedRowKeys;
onRowSelectionChange?.(selectedRowKeys, selectedRows);
},
renderCell: (checked, record, index, originNode) => {
if (!dragSort && !showIndex) {
return originNode;
}
const current = props?.pagination?.current;
const pageSize = props?.pagination?.pageSize || 20;
if (current) {
index = index + (current - 1) * pageSize;
}
return (
<div
className={classNames(
checked ? 'checked' : null,
css`
position: relative;
display: flex;
align-items: center;
@ -269,27 +307,27 @@ export const Table: any = observer((props: any) => {
}
}
`,
)}
>
<div
className={classNames(
checked ? 'checked' : null,
css`
)}
>
<div
className={classNames(
checked ? 'checked' : null,
css`
position: relative;
display: flex;
align-items: center;
justify-content: space-evenly;
`,
)}
>
{dragSort && <SortHandle id={getRowKey(record)} />}
{showIndex && <TableIndex index={index} />}
</div>
<div
className={classNames(
'nb-origin-node',
checked ? 'checked' : null,
css`
)}
>
{dragSort && <SortHandle id={getRowKey(record)} />}
{showIndex && <TableIndex index={index} />}
</div>
<div
className={classNames(
'nb-origin-node',
checked ? 'checked' : null,
css`
position: absolute;
right: 50%;
transform: translateX(50%);
@ -297,26 +335,31 @@ export const Table: any = observer((props: any) => {
display: none;
}
`,
)}
>
{originNode}
)}
>
{originNode}
</div>
</div>
</div>
);
},
...rowSelection,
}
);
},
...rowSelection,
}
: undefined,
};
const SortableWrapper = useCallback<React.FC>(({ children }) => {
return dragSort ? React.createElement(SortableContext, {
items: field.value.map(getRowKey),
children: children,
}) : React.createElement(React.Fragment, {
children
})
}, [field, dragSort])
const SortableWrapper = useCallback<React.FC>(
({ children }) => {
return dragSort
? React.createElement(SortableContext, {
items: field.value.map(getRowKey),
children: children,
})
: React.createElement(React.Fragment, {
children,
});
},
[field, dragSort],
);
return (
<div
@ -343,6 +386,13 @@ export const Table: any = observer((props: any) => {
dataSource={field?.value?.slice?.()}
/>
</SortableWrapper>
{field.errors.length > 0 && (
<div className="ant-formily-item-error-help ant-formily-item-help ant-formily-item-help-enter ant-formily-item-help-enter-active">
{field.errors.map((error) => {
return error.messages.map((message) => <div>{message}</div>);
})}
</div>
)}
</div>
);
});

View File

@ -1,3 +1,4 @@
import { Field } from '@formily/core';
import { observer, useField, useFieldSchema, useForm } from '@formily/react';
import React, { useEffect } from 'react';
import { useFormBlockContext } from '../../../block-provider';
@ -8,7 +9,7 @@ import { ActionBar } from '../action';
export const TableField: any = observer((props) => {
const fieldSchema = useFieldSchema();
const { getField } = useCollection();
const field = useField();
const field = useField<Field>();
const collectionField = getField(fieldSchema.name);
const compile = useCompile();
const ctx = useFormBlockContext();
@ -21,6 +22,9 @@ export const TableField: any = observer((props) => {
ctx.field.added.add(fieldSchema.name);
}
}, []);
useEffect(() => {
field.decoratorProps.asterisk = fieldSchema.required;
}, [fieldSchema.required]);
return <div>{props.children}</div>;
});