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

View File

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

View File

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

View File

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