Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
...base,
rules: {
...base.rules,
'arrow-parens': 0,
'no-confusing-arrow': 0,
'no-template-curly-in-string': 0,
'prefer-promise-reject-errors': 0,
Expand Down
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"arrowParens": "avoid",
"endOfLine": "lf",
"semi": true,
"singleQuote": true,
Expand Down
12 changes: 12 additions & 0 deletions examples/list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ const Demo = () => {
}}
style={{ border: '1px solid red', padding: 15 }}
preserve={false}
initialValues={{
users: ['little'],
}}
>
<Form.Field shouldUpdate>{() => JSON.stringify(form.getFieldsValue(), null, 2)}</Form.Field>

Expand Down Expand Up @@ -101,6 +104,15 @@ const Demo = () => {
>
Set List Value
</button>

<button
type="button"
onClick={() => {
console.log('`users` touched:', form.isFieldTouched('users'));
}}
>
Is List touched
</button>
</div>
</div>
);
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"enzyme-to-json": "^3.1.4",
"father": "^2.13.6",
"np": "^5.0.3",
"prettier": "^2.1.2",
"react": "^16.14.0",
"react-dnd": "^8.0.3",
"react-dnd-html5-backend": "^8.0.3",
Expand Down
5 changes: 5 additions & 0 deletions src/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ export interface InternalFieldProps<Values = any> {
/** @private Passed by Form.List props. Do not use since it will break by path check. */
isListField?: boolean;

/** @private Passed by Form.List props. Do not use since it will break by path check. */
isList?: boolean;

/** @private Pass context as prop instead of context api
* since class component can not get context in constructor */
fieldContext: InternalFormInstance;
Expand Down Expand Up @@ -361,6 +364,8 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F

public isListField = () => this.props.isListField;

public isList = () => this.props.isList;

// ============================= Child Component =============================
public getMeta = (): Meta => {
// Make error & validating in cache to save perf
Expand Down
8 changes: 7 additions & 1 deletion src/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,13 @@ const List: React.FunctionComponent<ListProps> = ({ name, children, rules, valid

return (
<FieldContext.Provider value={{ ...context, prefixName }}>
<Field name={[]} shouldUpdate={shouldUpdate} rules={rules} validateTrigger={validateTrigger}>
<Field
name={[]}
shouldUpdate={shouldUpdate}
rules={rules}
validateTrigger={validateTrigger}
isList
>
{({ value = [], onChange }, meta) => {
const { getFieldValue } = context;
const getNewValue = () => {
Expand Down
1 change: 1 addition & 0 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export interface FieldEntity {
isFieldDirty: () => boolean;
isFieldValidating: () => boolean;
isListField: () => boolean;
isList: () => boolean;
validateRules: (options?: ValidateOptions) => Promise<string[]>;
getMeta: () => Meta;
getNamePath: () => InternalNamePath;
Expand Down
53 changes: 36 additions & 17 deletions src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,11 +211,11 @@ export class FormStore {
const namePath =
'INVALIDATE_NAME_PATH' in entity ? entity.INVALIDATE_NAME_PATH : entity.getNamePath();

// Ignore when it's a list item and not specific the namePath,
// since parent field is already take in count
if (!nameList && (entity as FieldEntity).isListField?.()) {
return;
}
// Ignore when it's a list item and not specific the namePath,
// since parent field is already take in count
if (!nameList && (entity as FieldEntity).isListField?.()) {
return;
}

if (!filterFunc) {
filteredNameList.push(namePath);
Expand Down Expand Up @@ -287,22 +287,41 @@ export class FormStore {
isAllFieldsTouched = arg1;
}

const testTouched = (field: FieldEntity) => {
// Not provide `nameList` will check all the fields
if (!namePathList) {
return field.isFieldTouched();
}
const fieldEntities = this.getFieldEntities(true);
const isFieldTouched = (field: FieldEntity) => field.isFieldTouched();

// ===== Will get fully compare when not config namePathList =====
if (!namePathList) {
return isAllFieldsTouched
? fieldEntities.every(isFieldTouched)
: fieldEntities.some(isFieldTouched);
}

// Generate a nest tree for validate
const map = new NameMap<FieldEntity[]>();
namePathList.forEach(shortNamePath => {
map.set(shortNamePath, []);
});

fieldEntities.forEach(field => {
const fieldNamePath = field.getNamePath();
if (containsNamePath(namePathList, fieldNamePath)) {
return field.isFieldTouched();
}
return isAllFieldsTouched;
};

// Find matched entity and put into list
namePathList.forEach(shortNamePath => {
if (shortNamePath.every((nameUnit, i) => fieldNamePath[i] === nameUnit)) {
map.update(shortNamePath, list => [...list, field]);
}
});
});

// Check if NameMap value is touched
const isNamePathListTouched = (entities: FieldEntity[]) => entities.some(isFieldTouched);

const namePathListEntities = map.map(({ value }) => value);

return isAllFieldsTouched
? this.getFieldEntities(true).every(testTouched)
: this.getFieldEntities(true).some(testTouched);
? namePathListEntities.every(isNamePathListTouched)
: namePathListEntities.some(isNamePathListTouched);
};

private isFieldTouched = (name: NamePath) => {
Expand Down
95 changes: 94 additions & 1 deletion tests/list.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { mount, ReactWrapper } from 'enzyme';
import { resetWarned } from 'rc-util/lib/warning';
import Form, { Field, List, FormProps } from '../src';
import { ListField, ListOperations, ListProps } from '../src/List';
import { Meta } from '../src/interface';
import { FormInstance, Meta } from '../src/interface';
import { Input } from './common/InfoField';
import { changeValue, getField } from './common';
import timeout from './common/timeout';
Expand Down Expand Up @@ -646,4 +646,97 @@ describe('Form.List', () => {
wrapper.find('button').simulate('click');
expect(onValuesChange).toHaveBeenCalledWith(expect.anything(), { list: [{ first: 'light' }] });
});

describe('isFieldTouched edge case', () => {
it('virtual object', () => {
const formRef = React.createRef<FormInstance>();
const wrapper = mount(
<Form ref={formRef}>
<Form.Field name={['user', 'name']}>
<Input />
</Form.Field>
<Form.Field name={['user', 'age']}>
<Input />
</Form.Field>
</Form>,
);

// Not changed
expect(formRef.current.isFieldTouched('user')).toBeFalsy();
expect(formRef.current.isFieldsTouched(['user'], false)).toBeFalsy();
expect(formRef.current.isFieldsTouched(['user'], true)).toBeFalsy();

// Changed
wrapper
.find('input')
.first()
.simulate('change', { target: { value: '' } });

expect(formRef.current.isFieldTouched('user')).toBeTruthy();
expect(formRef.current.isFieldsTouched(['user'], false)).toBeTruthy();
expect(formRef.current.isFieldsTouched(['user'], true)).toBeTruthy();
});

it('List children change', () => {
const [wrapper] = generateForm(
fields => (
<div>
{fields.map(field => (
<Field {...field}>
<Input />
</Field>
))}
</div>
),
{
initialValues: { list: ['light', 'bamboo'] },
},
);

// Not changed yet
expect(form.isFieldTouched('list')).toBeFalsy();
expect(form.isFieldsTouched(['list'], false)).toBeFalsy();
expect(form.isFieldsTouched(['list'], true)).toBeFalsy();

// Change children value
wrapper
.find('input')
.first()
.simulate('change', { target: { value: 'little' } });

expect(form.isFieldTouched('list')).toBeTruthy();
expect(form.isFieldsTouched(['list'], false)).toBeTruthy();
expect(form.isFieldsTouched(['list'], true)).toBeTruthy();
});

it('List self change', () => {
const [wrapper] = generateForm((fields, opt) => (
<div>
{fields.map(field => (
<Field {...field}>
<Input />
</Field>
))}
<button
type="button"
onClick={() => {
opt.add();
}}
/>
</div>
));

// Not changed yet
expect(form.isFieldTouched('list')).toBeFalsy();
expect(form.isFieldsTouched(['list'], false)).toBeFalsy();
expect(form.isFieldsTouched(['list'], true)).toBeFalsy();

// Change children value
wrapper.find('button').simulate('click');

expect(form.isFieldTouched('list')).toBeTruthy();
expect(form.isFieldsTouched(['list'], false)).toBeTruthy();
expect(form.isFieldsTouched(['list'], true)).toBeTruthy();
});
});
});