add all frontend files

This commit is contained in:
2026-01-17 15:16:36 -05:00
parent ff16ae7858
commit e40287e4aa
25704 changed files with 1935289 additions and 0 deletions

21
node_modules/rc-field-form/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019-present react-component
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

286
node_modules/rc-field-form/README.md generated vendored Normal file
View File

@@ -0,0 +1,286 @@
# rc-field-form
React Performance First Form Component.
[![NPM version][npm-image]][npm-url] [![dumi](https://img.shields.io/badge/docs%20by-dumi-blue?style=flat-square)](https://github.com/umijs/dumi) [![build status][github-actions-image]][github-actions-url] [![Codecov][codecov-image]][codecov-url] [![npm download][download-image]][download-url]
[npm-image]: http://img.shields.io/npm/v/rc-field-form.svg?style=flat-square
[npm-url]: http://npmjs.org/package/rc-field-form
[github-actions-image]: https://github.com/react-component/field-form/workflows/CI/badge.svg
[github-actions-url]: https://github.com/react-component/field-form/actions
[codecov-image]: https://img.shields.io/codecov/c/github/react-component/field-form/master.svg?style=flat-square
[codecov-url]: https://codecov.io/gh/react-component/field-form/branch/master
[download-image]: https://img.shields.io/npm/dm/rc-field-form.svg?style=flat-square
[download-url]: https://npmjs.org/package/rc-field-form
## Development
```bash
npm install
npm start
open http://localhost:8000
```
## Feature
- Support react.js and even react-native
- Validate fields with [@rc-component/async-validator](https://github.com/react-component/async-validator/)
## Install
[![rc-field-form](https://nodei.co/npm/rc-field-form.png)](https://npmjs.org/package/rc-field-form)
## Usage
```js | pure
import Form, { Field } from 'rc-field-form';
const Input = ({ value = '', ...props }) => <input value={value} {...props} />;
const Demo = () => {
return (
<Form
onFinish={values => {
console.log('Finish:', values);
}}
>
<Field name="username">
<Input placeholder="Username" />
</Field>
<Field name="password">
<Input placeholder="Password" />
</Field>
<button>Submit</button>
</Form>
);
};
export default Demo;
```
## 🔥 API
We use typescript to create the Type definition. You can view directly in IDE. But you can still check the type definition [here](https://github.com/react-component/field-form/blob/master/src/interface.ts).
### Form
| Prop | Description | Type | Default |
| ---------------- | -------------------------------------------------- | -------------------------------------------- | ---------------- |
| component | Customize Form render component | string \| Component \| false | form |
| fields | Control Form fields status. Only use when in Redux | [FieldData](#fielddata)[] | - |
| form | Set form instance created by `useForm` | [FormInstance](#useform) | `Form.useForm()` |
| initialValues | Initial value of Form | Object | - |
| name | Config name with [FormProvider](#formprovider) | string | - |
| preserve | Preserve value when field removed | boolean | false |
| validateMessages | Set validate message template | [ValidateMessages](#validatemessages) | - |
| onFieldsChange | Trigger when any value of Field changed | (changedFields, allFields) => void | - |
| onFinish | Trigger when form submit and success | (values) => void | - |
| onFinishFailed | Trigger when form submit and failed | ({ values, errorFields, outOfDate }) => void | - |
| onValuesChange | Trigger when any value of Field changed | (changedValues, values) => void | - |
### Field
| Prop | Description | Type | Default |
| ----------------- | ----------------------------------------------------------------------------- | ---------------------------------------------- | -------- |
| dependencies | Will re-render if dependencies changed | [NamePath](#namepath)[] | - |
| getValueFromEvent | Specify how to get value from event | (..args: any[]) => any | - |
| getValueProps | Customize additional props with value. This prop will disable `valuePropName` | (value) => any | - |
| initialValue | Field initial value | any | - |
| name | Field name path | [NamePath](#namepath) | - |
| normalize | Normalize value before update | (value, prevValue, prevValues) => any | - |
| preserve | Preserve value when field removed | boolean | false |
| rules | Validate rules | [Rule](#rule)[] | - |
| shouldUpdate | Check if Field should update | boolean \| (prevValues, nextValues) => boolean | - |
| trigger | Collect value update by event trigger | string | onChange |
| validateTrigger | Config trigger point with rule validate | string \| string[] | onChange |
| valuePropName | Config value mapping prop with element | string | value |
### List
| Prop | Description | Type | Default |
| -------- | ------------------------------- | ------------------------------------------------------------------------------------------------------- | ------- |
| name | List field name path | [NamePath](#namepath)[] | - |
| children | Render props for listing fields | (fields: { name: [NamePath](#namepath) }[], operations: [ListOperations](#listoperations)) => ReactNode | - |
### useForm
Form component default create an form instance by `Form.useForm`. But you can create it and pass to Form also. This allow you to call some function on the form instance.
```jsx | pure
const Demo = () => {
const [form] = Form.useForm();
return <Form form={form} />;
};
```
For class component user, you can use `ref` to get form instance:
```jsx | pure
class Demo extends React.Component {
setRef = form => {
// Form instance here
};
render() {
return <Form ref={this.setRef} />;
}
}
```
| Prop | Description | Type |
| ----------------- | ------------------------------------------ | -------------------------------------------------------------------------- |
| getFieldValue | Get field value by name path | (name: [NamePath](#namepath)) => any |
| getFieldsValue | Get list of field values by name path list | (nameList?: ([NamePath](#namepath)[]) => any) \| true |
| getFieldError | Get field errors by name path | (name: [NamePath](#namepath)) => string[] |
| getFieldsError | Get list of field errors by name path list | (nameList?: [NamePath](#namepath)[]) => FieldError[] |
| isFieldsTouched | Check if list of fields are touched | (nameList?: [NamePath](#namepath)[], allTouched?: boolean) => boolean |
| isFieldTouched | Check if a field is touched | (name: [NamePath](#namepath)) => boolean |
| isFieldValidating | Check if a field is validating | (name: [NamePath](#namepath)) => boolean |
| resetFields | Reset fields status | (fields?: [NamePath](#namepath)[]) => void |
| setFields | Set fields status | (fields: FieldData[]) => void |
| setFieldsValue | Set fields value | (values) => void |
| submit | Trigger form submit | () => void |
| validateFields | Trigger fields to validate | (nameList?: [NamePath](#namepath)[], options?: ValidateOptions) => Promise |
### FormProvider
| Prop | Description | Type | Default |
| ---------------- | ----------------------------------------- | ---------------------------------------- | ------- |
| validateMessages | Config global `validateMessages` template | [ValidateMessages](#validatemessages) | - |
| onFormChange | Trigger by named form fields change | (name, { changedFields, forms }) => void | - |
| onFormFinish | Trigger by named form fields finish | (name, { values, forms }) => void | - |
## 📋 Interface
### NamePath
| Type |
| ---------------------------------------- |
| string \| number \| (string \| number)[] |
### FieldData
| Prop | Type |
| ---------- | ---------------------------------------- |
| touched | boolean |
| validating | boolean |
| errors | string[] |
| name | string \| number \| (string \| number)[] |
| value | any |
### Rule
| Prop | Type |
| --------------- | ----------------------------------------------------------------------------------------------- |
| enum | any[] |
| len | number |
| max | number |
| message | string |
| min | number |
| pattern | RegExp |
| required | boolean |
| transform | (value) => any |
| type | string |
| validator | ([rule](#rule), value, callback: (error?: string) => void, [form](#useform)) => Promise \| void |
| whitespace | boolean |
| validateTrigger | string \| string[] |
#### validator
To keep sync with `rc-form` legacy usage of `validator`, we still provides `callback` to trigger validate finished. But in `rc-field-form`, we strongly recommend to return a Promise instead.
### ListOperations
| Prop | Type |
| ------ | ------------------------ |
| add | (initValue: any) => void |
| remove | (index: number) => void |
### ValidateMessages
Validate Messages provides a list of error template. You can ref [here](https://github.com/react-component/field-form/blob/master/src/utils/messages.ts) for fully default templates.
| Prop | Description |
| ------- | ------------------- |
| enum | Rule `enum` prop |
| len | Rule `len` prop |
| max | Rule `max` prop |
| min | Rule `min` prop |
| name | Field name |
| pattern | Rule `pattern` prop |
| type | Rule `type` prop |
## Different with `rc-form`
`rc-field-form` is try to keep sync with `rc-form` in api level, but there still have something to change:
### 1. Field will not keep snyc with `initialValues` when un-touched
In `rc-form`, field value will get from `initialValues` if user not operate on it.
It's a bug but user use as a feature which makes fixing will be a breaking change and we have to keep it.
In Field Form, this bug will not exist anymore. If you want to change a field value, use `setFieldsValue` instead.
### 2. Remove Field will not clean up related value
We do lots of logic to clean up the value when Field removed before. But with user feedback, remove exist value increase the additional work to keep value back with conditional field.
### 3. Nest name use array instead of string
In `rc-form`, we support like `user.name` to be a name and convert value to `{ user: { name: 'Bamboo' } }`. This makes '.' always be the route of variable, this makes developer have to do additional work if name is real contains a point like `app.config.start` to be `app_config_start` and parse back to point when submit.
Field Form will only trade `['user', 'name']` to be `{ user: { name: 'Bamboo' } }`, and `user.name` to be `{ ['user.name']: 'Bamboo' }`.
### 4. Remove `validateFieldsAndScroll`
Since `findDomNode` is marked as warning in [StrictMode](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage). It seems over control of Form component.
We decide to remove `validateFieldsAndScroll` method and you should handle it with you own logic:
```jsx | pure
<Form>
<Field name="username">
<input ref={this.inputRef} />
</Field>
</Form>
```
### 5. `getFieldsError` always return array
`rc-form` returns `null` when no error happen. This makes user have to do some additional code like:
```js | pure
(form.getFieldsError('fieldName') || []).forEach(() => {
// Do something...
});
```
Now `getFieldsError` will return `[]` if no errors.
### 6. Remove `callback` with `validateFields`
Since ES8 is support `async/await`, that's no reason not to use it. Now you can easily handle your validate logic:
```js | pure
async function() {
try {
const values = await form.validateFields();
console.log(values);
} catch (errorList) {
errorList.forEach(({ name, errors }) => {
// Do something...
});
}
}
```
**Notice: Now if your validator return an `Error(message)`, not need to get error by `e => e.message`. FieldForm will handle this.**
### 7. `preserve` is default to false
In `rc-form` you should use `preserve` to keep a value cause Form will auto remove a value from Field removed. Field Form will always keep the value in the Form whatever Field removed. But you can still use `preserve=false` to disable value keeping since `1.5.0`.
### 8. `setFields` not trigger `onFieldsChange` and `setFieldsValue` not trigger `onValuesChange`
In `rc-form`, we hope to help user auto trigger change event by setting to make redux dispatch easier, but it's not good design since it makes code logic couping.
Additionally, user control update trigger `onFieldsChange` & `onValuesChange` event has potential dead loop risk.

54
node_modules/rc-field-form/es/Field.d.ts generated vendored Normal file
View File

@@ -0,0 +1,54 @@
import * as React from 'react';
import type { EventArgs, FormInstance, InternalFormInstance, InternalNamePath, Meta, NamePath, Rule, Store, StoreValue } from './interface';
export type ShouldUpdate<Values = any> = boolean | ((prevValues: Values, nextValues: Values, info: {
source?: string;
}) => boolean);
interface ChildProps {
[name: string]: any;
}
export type MetaEvent = Meta & {
destroy?: boolean;
};
export interface InternalFieldProps<Values = any> {
children?: React.ReactElement | ((control: ChildProps, meta: Meta, form: FormInstance<Values>) => React.ReactNode);
/**
* Set up `dependencies` field.
* When dependencies field update and current field is touched,
* will trigger validate rules and render.
*/
dependencies?: NamePath[];
getValueFromEvent?: (...args: EventArgs) => StoreValue;
name?: InternalNamePath;
normalize?: (value: StoreValue, prevValue: StoreValue, allValues: Store) => StoreValue;
rules?: Rule[];
shouldUpdate?: ShouldUpdate<Values>;
trigger?: string;
validateTrigger?: string | string[] | false;
/**
* Trigger will after configured milliseconds.
*/
validateDebounce?: number;
validateFirst?: boolean | 'parallel';
valuePropName?: string;
getValueProps?: (value: StoreValue) => Record<string, unknown>;
messageVariables?: Record<string, string>;
initialValue?: any;
onReset?: () => void;
onMetaChange?: (meta: MetaEvent) => void;
preserve?: boolean;
/** @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;
}
export interface FieldProps<Values = any> extends Omit<InternalFieldProps<Values>, 'name' | 'fieldContext'> {
name?: NamePath<Values>;
}
export interface FieldState {
resetCount: number;
}
declare function WrapperField<Values = any>({ name, ...restProps }: FieldProps<Values>): React.JSX.Element;
export default WrapperField;

614
node_modules/rc-field-form/es/Field.js generated vendored Normal file
View File

@@ -0,0 +1,614 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
var _excluded = ["name"];
import toChildrenArray from "rc-util/es/Children/toArray";
import isEqual from "rc-util/es/isEqual";
import warning from "rc-util/es/warning";
import * as React from 'react';
import FieldContext, { HOOK_MARK } from "./FieldContext";
import ListContext from "./ListContext";
import { toArray } from "./utils/typeUtil";
import { validateRules } from "./utils/validateUtil";
import { containsNamePath, defaultGetValueFromEvent, getNamePath, getValue } from "./utils/valueUtil";
var EMPTY_ERRORS = [];
function requireUpdate(shouldUpdate, prev, next, prevValue, nextValue, info) {
if (typeof shouldUpdate === 'function') {
return shouldUpdate(prev, next, 'source' in info ? {
source: info.source
} : {});
}
return prevValue !== nextValue;
}
// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
// We use Class instead of Hooks here since it will cost much code by using Hooks.
var Field = /*#__PURE__*/function (_React$Component) {
_inherits(Field, _React$Component);
var _super = _createSuper(Field);
// ============================== Subscriptions ==============================
function Field(props) {
var _this;
_classCallCheck(this, Field);
_this = _super.call(this, props);
// Register on init
_defineProperty(_assertThisInitialized(_this), "state", {
resetCount: 0
});
_defineProperty(_assertThisInitialized(_this), "cancelRegisterFunc", null);
_defineProperty(_assertThisInitialized(_this), "mounted", false);
/**
* Follow state should not management in State since it will async update by React.
* This makes first render of form can not get correct state value.
*/
_defineProperty(_assertThisInitialized(_this), "touched", false);
/**
* Mark when touched & validated. Currently only used for `dependencies`.
* Note that we do not think field with `initialValue` is dirty
* but this will be by `isFieldDirty` func.
*/
_defineProperty(_assertThisInitialized(_this), "dirty", false);
_defineProperty(_assertThisInitialized(_this), "validatePromise", void 0);
_defineProperty(_assertThisInitialized(_this), "prevValidating", void 0);
_defineProperty(_assertThisInitialized(_this), "errors", EMPTY_ERRORS);
_defineProperty(_assertThisInitialized(_this), "warnings", EMPTY_ERRORS);
_defineProperty(_assertThisInitialized(_this), "cancelRegister", function () {
var _this$props = _this.props,
preserve = _this$props.preserve,
isListField = _this$props.isListField,
name = _this$props.name;
if (_this.cancelRegisterFunc) {
_this.cancelRegisterFunc(isListField, preserve, getNamePath(name));
}
_this.cancelRegisterFunc = null;
});
// ================================== Utils ==================================
_defineProperty(_assertThisInitialized(_this), "getNamePath", function () {
var _this$props2 = _this.props,
name = _this$props2.name,
fieldContext = _this$props2.fieldContext;
var _fieldContext$prefixN = fieldContext.prefixName,
prefixName = _fieldContext$prefixN === void 0 ? [] : _fieldContext$prefixN;
return name !== undefined ? [].concat(_toConsumableArray(prefixName), _toConsumableArray(name)) : [];
});
_defineProperty(_assertThisInitialized(_this), "getRules", function () {
var _this$props3 = _this.props,
_this$props3$rules = _this$props3.rules,
rules = _this$props3$rules === void 0 ? [] : _this$props3$rules,
fieldContext = _this$props3.fieldContext;
return rules.map(function (rule) {
if (typeof rule === 'function') {
return rule(fieldContext);
}
return rule;
});
});
_defineProperty(_assertThisInitialized(_this), "refresh", function () {
if (!_this.mounted) return;
/**
* Clean up current node.
*/
_this.setState(function (_ref) {
var resetCount = _ref.resetCount;
return {
resetCount: resetCount + 1
};
});
});
// Event should only trigger when meta changed
_defineProperty(_assertThisInitialized(_this), "metaCache", null);
_defineProperty(_assertThisInitialized(_this), "triggerMetaEvent", function (destroy) {
var onMetaChange = _this.props.onMetaChange;
if (onMetaChange) {
var _meta = _objectSpread(_objectSpread({}, _this.getMeta()), {}, {
destroy: destroy
});
if (!isEqual(_this.metaCache, _meta)) {
onMetaChange(_meta);
}
_this.metaCache = _meta;
} else {
_this.metaCache = null;
}
});
// ========================= Field Entity Interfaces =========================
// Trigger by store update. Check if need update the component
_defineProperty(_assertThisInitialized(_this), "onStoreChange", function (prevStore, namePathList, info) {
var _this$props4 = _this.props,
shouldUpdate = _this$props4.shouldUpdate,
_this$props4$dependen = _this$props4.dependencies,
dependencies = _this$props4$dependen === void 0 ? [] : _this$props4$dependen,
onReset = _this$props4.onReset;
var store = info.store;
var namePath = _this.getNamePath();
var prevValue = _this.getValue(prevStore);
var curValue = _this.getValue(store);
var namePathMatch = namePathList && containsNamePath(namePathList, namePath);
// `setFieldsValue` is a quick access to update related status
if (info.type === 'valueUpdate' && info.source === 'external' && !isEqual(prevValue, curValue)) {
_this.touched = true;
_this.dirty = true;
_this.validatePromise = null;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
}
switch (info.type) {
case 'reset':
if (!namePathList || namePathMatch) {
// Clean up state
_this.touched = false;
_this.dirty = false;
_this.validatePromise = undefined;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
onReset === null || onReset === void 0 || onReset();
_this.refresh();
return;
}
break;
/**
* In case field with `preserve = false` nest deps like:
* - A = 1 => show B
* - B = 1 => show C
* - Reset A, need clean B, C
*/
case 'remove':
{
if (shouldUpdate && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
case 'setField':
{
var data = info.data;
if (namePathMatch) {
if ('touched' in data) {
_this.touched = data.touched;
}
if ('validating' in data && !('originRCField' in data)) {
_this.validatePromise = data.validating ? Promise.resolve([]) : null;
}
if ('errors' in data) {
_this.errors = data.errors || EMPTY_ERRORS;
}
if ('warnings' in data) {
_this.warnings = data.warnings || EMPTY_ERRORS;
}
_this.dirty = true;
_this.triggerMetaEvent();
_this.reRender();
return;
} else if ('value' in data && containsNamePath(namePathList, namePath, true)) {
// Contains path with value should also check
_this.reRender();
return;
}
// Handle update by `setField` with `shouldUpdate`
if (shouldUpdate && !namePath.length && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
case 'dependenciesUpdate':
{
/**
* Trigger when marked `dependencies` updated. Related fields will all update
*/
var dependencyList = dependencies.map(getNamePath);
// No need for `namePathMath` check and `shouldUpdate` check, since `valueUpdate` will be
// emitted earlier and they will work there
// If set it may cause unnecessary twice rerendering
if (dependencyList.some(function (dependency) {
return containsNamePath(info.relatedFields, dependency);
})) {
_this.reRender();
return;
}
break;
}
default:
// 1. If `namePath` exists in `namePathList`, means it's related value and should update
// For example <List name="list"><Field name={['list', 0]}></List>
// If `namePathList` is [['list']] (List value update), Field should be updated
// If `namePathList` is [['list', 0]] (Field value update), List shouldn't be updated
// 2.
// 2.1 If `dependencies` is set, `name` is not set and `shouldUpdate` is not set,
// don't use `shouldUpdate`. `dependencies` is view as a shortcut if `shouldUpdate`
// is not provided
// 2.2 If `shouldUpdate` provided, use customize logic to update the field
// else to check if value changed
if (namePathMatch || (!dependencies.length || namePath.length || shouldUpdate) && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
if (shouldUpdate === true) {
_this.reRender();
}
});
_defineProperty(_assertThisInitialized(_this), "validateRules", function (options) {
// We should fixed namePath & value to avoid developer change then by form function
var namePath = _this.getNamePath();
var currentValue = _this.getValue();
var _ref2 = options || {},
triggerName = _ref2.triggerName,
_ref2$validateOnly = _ref2.validateOnly,
validateOnly = _ref2$validateOnly === void 0 ? false : _ref2$validateOnly;
// Force change to async to avoid rule OOD under renderProps field
var rootPromise = Promise.resolve().then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var _this$props5, _this$props5$validate, validateFirst, messageVariables, validateDebounce, filteredRules, promise;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (_this.mounted) {
_context.next = 2;
break;
}
return _context.abrupt("return", []);
case 2:
_this$props5 = _this.props, _this$props5$validate = _this$props5.validateFirst, validateFirst = _this$props5$validate === void 0 ? false : _this$props5$validate, messageVariables = _this$props5.messageVariables, validateDebounce = _this$props5.validateDebounce; // Start validate
filteredRules = _this.getRules();
if (triggerName) {
filteredRules = filteredRules.filter(function (rule) {
return rule;
}).filter(function (rule) {
var validateTrigger = rule.validateTrigger;
if (!validateTrigger) {
return true;
}
var triggerList = toArray(validateTrigger);
return triggerList.includes(triggerName);
});
}
// Wait for debounce. Skip if no `triggerName` since its from `validateFields / submit`
if (!(validateDebounce && triggerName)) {
_context.next = 10;
break;
}
_context.next = 8;
return new Promise(function (resolve) {
setTimeout(resolve, validateDebounce);
});
case 8:
if (!(_this.validatePromise !== rootPromise)) {
_context.next = 10;
break;
}
return _context.abrupt("return", []);
case 10:
promise = validateRules(namePath, currentValue, filteredRules, options, validateFirst, messageVariables);
promise.catch(function (e) {
return e;
}).then(function () {
var ruleErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : EMPTY_ERRORS;
if (_this.validatePromise === rootPromise) {
var _ruleErrors$forEach;
_this.validatePromise = null;
// Get errors & warnings
var nextErrors = [];
var nextWarnings = [];
(_ruleErrors$forEach = ruleErrors.forEach) === null || _ruleErrors$forEach === void 0 || _ruleErrors$forEach.call(ruleErrors, function (_ref4) {
var warningOnly = _ref4.rule.warningOnly,
_ref4$errors = _ref4.errors,
errors = _ref4$errors === void 0 ? EMPTY_ERRORS : _ref4$errors;
if (warningOnly) {
nextWarnings.push.apply(nextWarnings, _toConsumableArray(errors));
} else {
nextErrors.push.apply(nextErrors, _toConsumableArray(errors));
}
});
_this.errors = nextErrors;
_this.warnings = nextWarnings;
_this.triggerMetaEvent();
_this.reRender();
}
});
return _context.abrupt("return", promise);
case 13:
case "end":
return _context.stop();
}
}, _callee);
})));
if (validateOnly) {
return rootPromise;
}
_this.validatePromise = rootPromise;
_this.dirty = true;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
// Force trigger re-render since we need sync renderProps with new meta
_this.reRender();
return rootPromise;
});
_defineProperty(_assertThisInitialized(_this), "isFieldValidating", function () {
return !!_this.validatePromise;
});
_defineProperty(_assertThisInitialized(_this), "isFieldTouched", function () {
return _this.touched;
});
_defineProperty(_assertThisInitialized(_this), "isFieldDirty", function () {
// Touched or validate or has initialValue
if (_this.dirty || _this.props.initialValue !== undefined) {
return true;
}
// Form set initialValue
var fieldContext = _this.props.fieldContext;
var _fieldContext$getInte = fieldContext.getInternalHooks(HOOK_MARK),
getInitialValue = _fieldContext$getInte.getInitialValue;
if (getInitialValue(_this.getNamePath()) !== undefined) {
return true;
}
return false;
});
_defineProperty(_assertThisInitialized(_this), "getErrors", function () {
return _this.errors;
});
_defineProperty(_assertThisInitialized(_this), "getWarnings", function () {
return _this.warnings;
});
_defineProperty(_assertThisInitialized(_this), "isListField", function () {
return _this.props.isListField;
});
_defineProperty(_assertThisInitialized(_this), "isList", function () {
return _this.props.isList;
});
_defineProperty(_assertThisInitialized(_this), "isPreserve", function () {
return _this.props.preserve;
});
// ============================= Child Component =============================
_defineProperty(_assertThisInitialized(_this), "getMeta", function () {
// Make error & validating in cache to save perf
_this.prevValidating = _this.isFieldValidating();
var meta = {
touched: _this.isFieldTouched(),
validating: _this.prevValidating,
errors: _this.errors,
warnings: _this.warnings,
name: _this.getNamePath(),
validated: _this.validatePromise === null
};
return meta;
});
// Only return validate child node. If invalidate, will do nothing about field.
_defineProperty(_assertThisInitialized(_this), "getOnlyChild", function (children) {
// Support render props
if (typeof children === 'function') {
var _meta2 = _this.getMeta();
return _objectSpread(_objectSpread({}, _this.getOnlyChild(children(_this.getControlled(), _meta2, _this.props.fieldContext))), {}, {
isFunction: true
});
}
// Filed element only
var childList = toChildrenArray(children);
if (childList.length !== 1 || ! /*#__PURE__*/React.isValidElement(childList[0])) {
return {
child: childList,
isFunction: false
};
}
return {
child: childList[0],
isFunction: false
};
});
// ============================== Field Control ==============================
_defineProperty(_assertThisInitialized(_this), "getValue", function (store) {
var getFieldsValue = _this.props.fieldContext.getFieldsValue;
var namePath = _this.getNamePath();
return getValue(store || getFieldsValue(true), namePath);
});
_defineProperty(_assertThisInitialized(_this), "getControlled", function () {
var childProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _this$props6 = _this.props,
name = _this$props6.name,
trigger = _this$props6.trigger,
validateTrigger = _this$props6.validateTrigger,
getValueFromEvent = _this$props6.getValueFromEvent,
normalize = _this$props6.normalize,
valuePropName = _this$props6.valuePropName,
getValueProps = _this$props6.getValueProps,
fieldContext = _this$props6.fieldContext;
var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : fieldContext.validateTrigger;
var namePath = _this.getNamePath();
var getInternalHooks = fieldContext.getInternalHooks,
getFieldsValue = fieldContext.getFieldsValue;
var _getInternalHooks = getInternalHooks(HOOK_MARK),
dispatch = _getInternalHooks.dispatch;
var value = _this.getValue();
var mergedGetValueProps = getValueProps || function (val) {
return _defineProperty({}, valuePropName, val);
};
var originTriggerFunc = childProps[trigger];
var valueProps = name !== undefined ? mergedGetValueProps(value) : {};
// warning when prop value is function
if (process.env.NODE_ENV !== 'production' && valueProps) {
Object.keys(valueProps).forEach(function (key) {
warning(typeof valueProps[key] !== 'function', "It's not recommended to generate dynamic function prop by `getValueProps`. Please pass it to child component directly (prop: ".concat(key, ")"));
});
}
var control = _objectSpread(_objectSpread({}, childProps), valueProps);
// Add trigger
control[trigger] = function () {
// Mark as touched
_this.touched = true;
_this.dirty = true;
_this.triggerMetaEvent();
var newValue;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (getValueFromEvent) {
newValue = getValueFromEvent.apply(void 0, args);
} else {
newValue = defaultGetValueFromEvent.apply(void 0, [valuePropName].concat(args));
}
if (normalize) {
newValue = normalize(newValue, value, getFieldsValue(true));
}
if (newValue !== value) {
dispatch({
type: 'updateValue',
namePath: namePath,
value: newValue
});
}
if (originTriggerFunc) {
originTriggerFunc.apply(void 0, args);
}
};
// Add validateTrigger
var validateTriggerList = toArray(mergedValidateTrigger || []);
validateTriggerList.forEach(function (triggerName) {
// Wrap additional function of component, so that we can get latest value from store
var originTrigger = control[triggerName];
control[triggerName] = function () {
if (originTrigger) {
originTrigger.apply(void 0, arguments);
}
// Always use latest rules
var rules = _this.props.rules;
if (rules && rules.length) {
// We dispatch validate to root,
// since it will update related data with other field with same name
dispatch({
type: 'validateField',
namePath: namePath,
triggerName: triggerName
});
}
};
});
return control;
});
if (props.fieldContext) {
var getInternalHooks = props.fieldContext.getInternalHooks;
var _getInternalHooks2 = getInternalHooks(HOOK_MARK),
initEntityValue = _getInternalHooks2.initEntityValue;
initEntityValue(_assertThisInitialized(_this));
}
return _this;
}
_createClass(Field, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this$props7 = this.props,
shouldUpdate = _this$props7.shouldUpdate,
fieldContext = _this$props7.fieldContext;
this.mounted = true;
// Register on init
if (fieldContext) {
var getInternalHooks = fieldContext.getInternalHooks;
var _getInternalHooks3 = getInternalHooks(HOOK_MARK),
registerField = _getInternalHooks3.registerField;
this.cancelRegisterFunc = registerField(this);
}
// One more render for component in case fields not ready
if (shouldUpdate === true) {
this.reRender();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.cancelRegister();
this.triggerMetaEvent(true);
this.mounted = false;
}
}, {
key: "reRender",
value: function reRender() {
if (!this.mounted) return;
this.forceUpdate();
}
}, {
key: "render",
value: function render() {
var resetCount = this.state.resetCount;
var children = this.props.children;
var _this$getOnlyChild = this.getOnlyChild(children),
child = _this$getOnlyChild.child,
isFunction = _this$getOnlyChild.isFunction;
// Not need to `cloneElement` since user can handle this in render function self
var returnChildNode;
if (isFunction) {
returnChildNode = child;
} else if ( /*#__PURE__*/React.isValidElement(child)) {
returnChildNode = /*#__PURE__*/React.cloneElement(child, this.getControlled(child.props));
} else {
warning(!child, '`children` of Field is not validate ReactElement.');
returnChildNode = child;
}
return /*#__PURE__*/React.createElement(React.Fragment, {
key: resetCount
}, returnChildNode);
}
}]);
return Field;
}(React.Component);
_defineProperty(Field, "contextType", FieldContext);
_defineProperty(Field, "defaultProps", {
trigger: 'onChange',
valuePropName: 'value'
});
function WrapperField(_ref6) {
var _restProps$isListFiel;
var name = _ref6.name,
restProps = _objectWithoutProperties(_ref6, _excluded);
var fieldContext = React.useContext(FieldContext);
var listContext = React.useContext(ListContext);
var namePath = name !== undefined ? getNamePath(name) : undefined;
var isMergedListField = (_restProps$isListFiel = restProps.isListField) !== null && _restProps$isListFiel !== void 0 ? _restProps$isListFiel : !!listContext;
var key = 'keep';
if (!isMergedListField) {
key = "_".concat((namePath || []).join('_'));
}
// Warning if it's a directly list field.
// We can still support multiple level field preserve.
if (process.env.NODE_ENV !== 'production' && restProps.preserve === false && isMergedListField && namePath.length <= 1) {
warning(false, '`preserve` should not apply on Form.List fields.');
}
return /*#__PURE__*/React.createElement(Field, _extends({
key: key,
name: namePath,
isListField: isMergedListField
}, restProps, {
fieldContext: fieldContext
}));
}
export default WrapperField;

5
node_modules/rc-field-form/es/FieldContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import * as React from 'react';
import type { InternalFormInstance } from './interface';
export declare const HOOK_MARK = "RC_FORM_INTERNAL_HOOKS";
declare const Context: React.Context<InternalFormInstance>;
export default Context;

43
node_modules/rc-field-form/es/FieldContext.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
import warning from "rc-util/es/warning";
import * as React from 'react';
export var HOOK_MARK = 'RC_FORM_INTERNAL_HOOKS';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var warningFunc = function warningFunc() {
warning(false, 'Can not find FormContext. Please make sure you wrap Field under Form.');
};
var Context = /*#__PURE__*/React.createContext({
getFieldValue: warningFunc,
getFieldsValue: warningFunc,
getFieldError: warningFunc,
getFieldWarning: warningFunc,
getFieldsError: warningFunc,
isFieldsTouched: warningFunc,
isFieldTouched: warningFunc,
isFieldValidating: warningFunc,
isFieldsValidating: warningFunc,
resetFields: warningFunc,
setFields: warningFunc,
setFieldValue: warningFunc,
setFieldsValue: warningFunc,
validateFields: warningFunc,
submit: warningFunc,
getInternalHooks: function getInternalHooks() {
warningFunc();
return {
dispatch: warningFunc,
initEntityValue: warningFunc,
registerField: warningFunc,
useSubscribe: warningFunc,
setInitialValues: warningFunc,
destroyForm: warningFunc,
setCallbacks: warningFunc,
registerWatch: warningFunc,
getFields: warningFunc,
setValidateMessages: warningFunc,
setPreserve: warningFunc,
getInitialValue: warningFunc
};
}
});
export default Context;

22
node_modules/rc-field-form/es/Form.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import type { Store, FormInstance, FieldData, ValidateMessages, Callbacks, FormRef } from './interface';
type BaseFormProps = Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onSubmit' | 'children'>;
type RenderProps = (values: Store, form: FormInstance) => JSX.Element | React.ReactNode;
export interface FormProps<Values = any> extends BaseFormProps {
initialValues?: Store;
form?: FormInstance<Values>;
children?: RenderProps | React.ReactNode;
component?: false | string | React.FC<any> | React.ComponentClass<any>;
fields?: FieldData[];
name?: string;
validateMessages?: ValidateMessages;
onValuesChange?: Callbacks<Values>['onValuesChange'];
onFieldsChange?: Callbacks<Values>['onFieldsChange'];
onFinish?: Callbacks<Values>['onFinish'];
onFinishFailed?: Callbacks<Values>['onFinishFailed'];
validateTrigger?: string | string[] | false;
preserve?: boolean;
clearOnDestroy?: boolean;
}
declare const Form: React.ForwardRefRenderFunction<FormRef, FormProps>;
export default Form;

147
node_modules/rc-field-form/es/Form.js generated vendored Normal file
View File

@@ -0,0 +1,147 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
var _excluded = ["name", "initialValues", "fields", "form", "preserve", "children", "component", "validateMessages", "validateTrigger", "onValuesChange", "onFieldsChange", "onFinish", "onFinishFailed", "clearOnDestroy"];
import * as React from 'react';
import useForm from "./useForm";
import FieldContext, { HOOK_MARK } from "./FieldContext";
import FormContext from "./FormContext";
import { isSimilar } from "./utils/valueUtil";
import ListContext from "./ListContext";
var Form = function Form(_ref, ref) {
var name = _ref.name,
initialValues = _ref.initialValues,
fields = _ref.fields,
form = _ref.form,
preserve = _ref.preserve,
children = _ref.children,
_ref$component = _ref.component,
Component = _ref$component === void 0 ? 'form' : _ref$component,
validateMessages = _ref.validateMessages,
_ref$validateTrigger = _ref.validateTrigger,
validateTrigger = _ref$validateTrigger === void 0 ? 'onChange' : _ref$validateTrigger,
onValuesChange = _ref.onValuesChange,
_onFieldsChange = _ref.onFieldsChange,
_onFinish = _ref.onFinish,
onFinishFailed = _ref.onFinishFailed,
clearOnDestroy = _ref.clearOnDestroy,
restProps = _objectWithoutProperties(_ref, _excluded);
var nativeElementRef = React.useRef(null);
var formContext = React.useContext(FormContext);
// We customize handle event since Context will makes all the consumer re-render:
// https://reactjs.org/docs/context.html#contextprovider
var _useForm = useForm(form),
_useForm2 = _slicedToArray(_useForm, 1),
formInstance = _useForm2[0];
var _getInternalHooks = formInstance.getInternalHooks(HOOK_MARK),
useSubscribe = _getInternalHooks.useSubscribe,
setInitialValues = _getInternalHooks.setInitialValues,
setCallbacks = _getInternalHooks.setCallbacks,
setValidateMessages = _getInternalHooks.setValidateMessages,
setPreserve = _getInternalHooks.setPreserve,
destroyForm = _getInternalHooks.destroyForm;
// Pass ref with form instance
React.useImperativeHandle(ref, function () {
return _objectSpread(_objectSpread({}, formInstance), {}, {
nativeElement: nativeElementRef.current
});
});
// Register form into Context
React.useEffect(function () {
formContext.registerForm(name, formInstance);
return function () {
formContext.unregisterForm(name);
};
}, [formContext, formInstance, name]);
// Pass props to store
setValidateMessages(_objectSpread(_objectSpread({}, formContext.validateMessages), validateMessages));
setCallbacks({
onValuesChange: onValuesChange,
onFieldsChange: function onFieldsChange(changedFields) {
formContext.triggerFormChange(name, changedFields);
if (_onFieldsChange) {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
_onFieldsChange.apply(void 0, [changedFields].concat(rest));
}
},
onFinish: function onFinish(values) {
formContext.triggerFormFinish(name, values);
if (_onFinish) {
_onFinish(values);
}
},
onFinishFailed: onFinishFailed
});
setPreserve(preserve);
// Set initial value, init store value when first mount
var mountRef = React.useRef(null);
setInitialValues(initialValues, !mountRef.current);
if (!mountRef.current) {
mountRef.current = true;
}
React.useEffect(function () {
return function () {
return destroyForm(clearOnDestroy);
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]);
// Prepare children by `children` type
var childrenNode;
var childrenRenderProps = typeof children === 'function';
if (childrenRenderProps) {
var _values = formInstance.getFieldsValue(true);
childrenNode = children(_values, formInstance);
} else {
childrenNode = children;
}
// Not use subscribe when using render props
useSubscribe(!childrenRenderProps);
// Listen if fields provided. We use ref to save prev data here to avoid additional render
var prevFieldsRef = React.useRef();
React.useEffect(function () {
if (!isSimilar(prevFieldsRef.current || [], fields || [])) {
formInstance.setFields(fields || []);
}
prevFieldsRef.current = fields;
}, [fields, formInstance]);
var formContextValue = React.useMemo(function () {
return _objectSpread(_objectSpread({}, formInstance), {}, {
validateTrigger: validateTrigger
});
}, [formInstance, validateTrigger]);
var wrapperNode = /*#__PURE__*/React.createElement(ListContext.Provider, {
value: null
}, /*#__PURE__*/React.createElement(FieldContext.Provider, {
value: formContextValue
}, childrenNode));
if (Component === false) {
return wrapperNode;
}
return /*#__PURE__*/React.createElement(Component, _extends({}, restProps, {
ref: nativeElementRef,
onSubmit: function onSubmit(event) {
event.preventDefault();
event.stopPropagation();
formInstance.submit();
},
onReset: function onReset(event) {
var _restProps$onReset;
event.preventDefault();
formInstance.resetFields();
(_restProps$onReset = restProps.onReset) === null || _restProps$onReset === void 0 || _restProps$onReset.call(restProps, event);
}
}), wrapperNode);
};
export default Form;

27
node_modules/rc-field-form/es/FormContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import * as React from 'react';
import type { ValidateMessages, FormInstance, FieldData, Store } from './interface';
export type Forms = Record<string, FormInstance>;
export interface FormChangeInfo {
changedFields: FieldData[];
forms: Forms;
}
export interface FormFinishInfo {
values: Store;
forms: Forms;
}
export interface FormProviderProps {
validateMessages?: ValidateMessages;
onFormChange?: (name: string, info: FormChangeInfo) => void;
onFormFinish?: (name: string, info: FormFinishInfo) => void;
children?: React.ReactNode;
}
export interface FormContextProps extends FormProviderProps {
triggerFormChange: (name: string, changedFields: FieldData[]) => void;
triggerFormFinish: (name: string, values: Store) => void;
registerForm: (name: string, form: FormInstance) => void;
unregisterForm: (name: string) => void;
}
declare const FormContext: React.Context<FormContextProps>;
declare const FormProvider: React.FunctionComponent<FormProviderProps>;
export { FormProvider };
export default FormContext;

57
node_modules/rc-field-form/es/FormContext.js generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import * as React from 'react';
var FormContext = /*#__PURE__*/React.createContext({
triggerFormChange: function triggerFormChange() {},
triggerFormFinish: function triggerFormFinish() {},
registerForm: function registerForm() {},
unregisterForm: function unregisterForm() {}
});
var FormProvider = function FormProvider(_ref) {
var validateMessages = _ref.validateMessages,
onFormChange = _ref.onFormChange,
onFormFinish = _ref.onFormFinish,
children = _ref.children;
var formContext = React.useContext(FormContext);
var formsRef = React.useRef({});
return /*#__PURE__*/React.createElement(FormContext.Provider, {
value: _objectSpread(_objectSpread({}, formContext), {}, {
validateMessages: _objectSpread(_objectSpread({}, formContext.validateMessages), validateMessages),
// =========================================================
// = Global Form Control =
// =========================================================
triggerFormChange: function triggerFormChange(name, changedFields) {
if (onFormChange) {
onFormChange(name, {
changedFields: changedFields,
forms: formsRef.current
});
}
formContext.triggerFormChange(name, changedFields);
},
triggerFormFinish: function triggerFormFinish(name, values) {
if (onFormFinish) {
onFormFinish(name, {
values: values,
forms: formsRef.current
});
}
formContext.triggerFormFinish(name, values);
},
registerForm: function registerForm(name, form) {
if (name) {
formsRef.current = _objectSpread(_objectSpread({}, formsRef.current), {}, _defineProperty({}, name, form));
}
formContext.registerForm(name, form);
},
unregisterForm: function unregisterForm(name) {
var newForms = _objectSpread({}, formsRef.current);
delete newForms[name];
formsRef.current = newForms;
formContext.unregisterForm(name);
}
})
}, children);
};
export { FormProvider };
export default FormContext;

23
node_modules/rc-field-form/es/List.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import * as React from 'react';
import type { NamePath, StoreValue, ValidatorRule, Meta } from './interface';
export interface ListField {
name: number;
key: number;
isListField: boolean;
}
export interface ListOperations {
add: (defaultValue?: StoreValue, index?: number) => void;
remove: (index: number | number[]) => void;
move: (from: number, to: number) => void;
}
export interface ListProps<Values = any> {
name: NamePath<Values>;
rules?: ValidatorRule[];
validateTrigger?: string | string[] | false;
initialValue?: any[];
children?: (fields: ListField[], operations: ListOperations, meta: Meta) => JSX.Element | React.ReactNode;
/** @private Passed by Form.List props. Do not use since it will break by path check. */
isListField?: boolean;
}
declare function List<Values = any>({ name, initialValue, children, rules, validateTrigger, isListField, }: ListProps<Values>): React.JSX.Element;
export default List;

149
node_modules/rc-field-form/es/List.js generated vendored Normal file
View File

@@ -0,0 +1,149 @@
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import * as React from 'react';
import warning from "rc-util/es/warning";
import FieldContext from "./FieldContext";
import Field from "./Field";
import { move as _move, getNamePath } from "./utils/valueUtil";
import ListContext from "./ListContext";
function List(_ref) {
var name = _ref.name,
initialValue = _ref.initialValue,
children = _ref.children,
rules = _ref.rules,
validateTrigger = _ref.validateTrigger,
isListField = _ref.isListField;
var context = React.useContext(FieldContext);
var wrapperListContext = React.useContext(ListContext);
var keyRef = React.useRef({
keys: [],
id: 0
});
var keyManager = keyRef.current;
var prefixName = React.useMemo(function () {
var parentPrefixName = getNamePath(context.prefixName) || [];
return [].concat(_toConsumableArray(parentPrefixName), _toConsumableArray(getNamePath(name)));
}, [context.prefixName, name]);
var fieldContext = React.useMemo(function () {
return _objectSpread(_objectSpread({}, context), {}, {
prefixName: prefixName
});
}, [context, prefixName]);
// List context
var listContext = React.useMemo(function () {
return {
getKey: function getKey(namePath) {
var len = prefixName.length;
var pathName = namePath[len];
return [keyManager.keys[pathName], namePath.slice(len + 1)];
}
};
}, [prefixName]);
// User should not pass `children` as other type.
if (typeof children !== 'function') {
warning(false, 'Form.List only accepts function as children.');
return null;
}
var shouldUpdate = function shouldUpdate(prevValue, nextValue, _ref2) {
var source = _ref2.source;
if (source === 'internal') {
return false;
}
return prevValue !== nextValue;
};
return /*#__PURE__*/React.createElement(ListContext.Provider, {
value: listContext
}, /*#__PURE__*/React.createElement(FieldContext.Provider, {
value: fieldContext
}, /*#__PURE__*/React.createElement(Field, {
name: [],
shouldUpdate: shouldUpdate,
rules: rules,
validateTrigger: validateTrigger,
initialValue: initialValue,
isList: true,
isListField: isListField !== null && isListField !== void 0 ? isListField : !!wrapperListContext
}, function (_ref3, meta) {
var _ref3$value = _ref3.value,
value = _ref3$value === void 0 ? [] : _ref3$value,
onChange = _ref3.onChange;
var getFieldValue = context.getFieldValue;
var getNewValue = function getNewValue() {
var values = getFieldValue(prefixName || []);
return values || [];
};
/**
* Always get latest value in case user update fields by `form` api.
*/
var operations = {
add: function add(defaultValue, index) {
// Mapping keys
var newValue = getNewValue();
if (index >= 0 && index <= newValue.length) {
keyManager.keys = [].concat(_toConsumableArray(keyManager.keys.slice(0, index)), [keyManager.id], _toConsumableArray(keyManager.keys.slice(index)));
onChange([].concat(_toConsumableArray(newValue.slice(0, index)), [defaultValue], _toConsumableArray(newValue.slice(index))));
} else {
if (process.env.NODE_ENV !== 'production' && (index < 0 || index > newValue.length)) {
warning(false, 'The second parameter of the add function should be a valid positive number.');
}
keyManager.keys = [].concat(_toConsumableArray(keyManager.keys), [keyManager.id]);
onChange([].concat(_toConsumableArray(newValue), [defaultValue]));
}
keyManager.id += 1;
},
remove: function remove(index) {
var newValue = getNewValue();
var indexSet = new Set(Array.isArray(index) ? index : [index]);
if (indexSet.size <= 0) {
return;
}
keyManager.keys = keyManager.keys.filter(function (_, keysIndex) {
return !indexSet.has(keysIndex);
});
// Trigger store change
onChange(newValue.filter(function (_, valueIndex) {
return !indexSet.has(valueIndex);
}));
},
move: function move(from, to) {
if (from === to) {
return;
}
var newValue = getNewValue();
// Do not handle out of range
if (from < 0 || from >= newValue.length || to < 0 || to >= newValue.length) {
return;
}
keyManager.keys = _move(keyManager.keys, from, to);
// Trigger store change
onChange(_move(newValue, from, to));
}
};
var listValue = value || [];
if (!Array.isArray(listValue)) {
listValue = [];
if (process.env.NODE_ENV !== 'production') {
warning(false, "Current value of '".concat(prefixName.join(' > '), "' is not an array type."));
}
}
return children(listValue.map(function (__, index) {
var key = keyManager.keys[index];
if (key === undefined) {
keyManager.keys[index] = keyManager.id;
key = keyManager.keys[index];
keyManager.id += 1;
}
return {
name: index,
key: key,
isListField: true
};
}), operations, meta);
})));
}
export default List;

7
node_modules/rc-field-form/es/ListContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import * as React from 'react';
import type { InternalNamePath } from './interface';
export interface ListContextProps {
getKey: (namePath: InternalNamePath) => [InternalNamePath[number], InternalNamePath];
}
declare const ListContext: React.Context<ListContextProps>;
export default ListContext;

3
node_modules/rc-field-form/es/ListContext.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import * as React from 'react';
var ListContext = /*#__PURE__*/React.createContext(null);
export default ListContext;

25
node_modules/rc-field-form/es/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import * as React from 'react';
import type { FormRef, FormInstance } from './interface';
import Field from './Field';
import List from './List';
import useForm from './useForm';
import type { FormProps } from './Form';
import { FormProvider } from './FormContext';
import FieldContext from './FieldContext';
import ListContext from './ListContext';
import useWatch from './useWatch';
declare const InternalForm: <Values = any>(props: FormProps<Values> & {
ref?: React.Ref<FormRef<Values>>;
}) => React.ReactElement;
type InternalFormType = typeof InternalForm;
interface RefFormType extends InternalFormType {
FormProvider: typeof FormProvider;
Field: typeof Field;
List: typeof List;
useForm: typeof useForm;
useWatch: typeof useWatch;
}
declare const RefForm: RefFormType;
export { Field, List, useForm, FormProvider, FieldContext, ListContext, useWatch };
export type { FormProps, FormInstance, FormRef };
export default RefForm;

18
node_modules/rc-field-form/es/index.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import * as React from 'react';
import Field from "./Field";
import List from "./List";
import useForm from "./useForm";
import FieldForm from "./Form";
import { FormProvider } from "./FormContext";
import FieldContext from "./FieldContext";
import ListContext from "./ListContext";
import useWatch from "./useWatch";
var InternalForm = /*#__PURE__*/React.forwardRef(FieldForm);
var RefForm = InternalForm;
RefForm.FormProvider = FormProvider;
RefForm.Field = Field;
RefForm.List = List;
RefForm.useForm = useForm;
RefForm.useWatch = useWatch;
export { Field, List, useForm, FormProvider, FieldContext, ListContext, useWatch };
export default RefForm;

265
node_modules/rc-field-form/es/interface.d.ts generated vendored Normal file
View File

@@ -0,0 +1,265 @@
import type { ReactElement } from 'react';
import type { DeepNamePath } from './namePathType';
import type { ReducerAction } from './useForm';
export type InternalNamePath = (string | number)[];
export type NamePath<T = any> = DeepNamePath<T>;
export type StoreValue = any;
export type Store = Record<string, StoreValue>;
export interface Meta {
touched: boolean;
validating: boolean;
errors: string[];
warnings: string[];
name: InternalNamePath;
validated: boolean;
}
export interface InternalFieldData extends Meta {
value: StoreValue;
}
/**
* Used by `setFields` config
*/
export interface FieldData<Values = any> extends Partial<Omit<InternalFieldData, 'name'>> {
name: NamePath<Values>;
}
export type RuleType = 'string' | 'number' | 'boolean' | 'method' | 'regexp' | 'integer' | 'float' | 'object' | 'enum' | 'date' | 'url' | 'hex' | 'email';
type Validator = (rule: RuleObject, value: StoreValue, callback: (error?: string) => void) => Promise<void | any> | void;
export type RuleRender = (form: FormInstance) => RuleObject;
export interface ValidatorRule {
warningOnly?: boolean;
message?: string | ReactElement;
validator: Validator;
}
interface BaseRule {
warningOnly?: boolean;
enum?: StoreValue[];
len?: number;
max?: number;
message?: string | ReactElement;
min?: number;
pattern?: RegExp;
required?: boolean;
transform?: (value: StoreValue) => StoreValue;
type?: RuleType;
whitespace?: boolean;
/** Customize rule level `validateTrigger`. Must be subset of Field `validateTrigger` */
validateTrigger?: string | string[];
}
type AggregationRule = BaseRule & Partial<ValidatorRule>;
interface ArrayRule extends Omit<AggregationRule, 'type'> {
type: 'array';
defaultField?: RuleObject;
}
export type RuleObject = AggregationRule | ArrayRule;
export type Rule = RuleObject | RuleRender;
export interface ValidateErrorEntity<Values = any> {
values: Values;
errorFields: {
name: InternalNamePath;
errors: string[];
}[];
outOfDate: boolean;
}
export interface FieldEntity {
onStoreChange: (store: Store, namePathList: InternalNamePath[] | null, info: ValuedNotifyInfo) => void;
isFieldTouched: () => boolean;
isFieldDirty: () => boolean;
isFieldValidating: () => boolean;
isListField: () => boolean;
isList: () => boolean;
isPreserve: () => boolean;
validateRules: (options?: InternalValidateOptions) => Promise<RuleError[]>;
getMeta: () => Meta;
getNamePath: () => InternalNamePath;
getErrors: () => string[];
getWarnings: () => string[];
props: {
name?: NamePath;
rules?: Rule[];
dependencies?: NamePath[];
initialValue?: any;
};
}
export interface FieldError {
name: InternalNamePath;
errors: string[];
warnings: string[];
}
export interface RuleError {
errors: string[];
rule: RuleObject;
}
export interface ValidateOptions {
/**
* Validate only and not trigger UI and Field status update
*/
validateOnly?: boolean;
/**
* Recursive validate. It will validate all the name path that contains the provided one.
* e.g. [['a']] will validate ['a'] , ['a', 'b'] and ['a', 1].
*/
recursive?: boolean;
/** Validate when a field is dirty (validated or touched) */
dirty?: boolean;
}
export type ValidateFields<Values = any> = {
(opt?: ValidateOptions): Promise<Values>;
(nameList?: NamePath[], opt?: ValidateOptions): Promise<Values>;
};
export interface InternalValidateOptions extends ValidateOptions {
triggerName?: string;
validateMessages?: ValidateMessages;
}
export type InternalValidateFields<Values = any> = {
(options?: InternalValidateOptions): Promise<Values>;
(nameList?: NamePath[], options?: InternalValidateOptions): Promise<Values>;
};
interface ValueUpdateInfo {
type: 'valueUpdate';
source: 'internal' | 'external';
}
interface ValidateFinishInfo {
type: 'validateFinish';
}
interface ResetInfo {
type: 'reset';
}
interface RemoveInfo {
type: 'remove';
}
interface SetFieldInfo {
type: 'setField';
data: FieldData;
}
interface DependenciesUpdateInfo {
type: 'dependenciesUpdate';
/**
* Contains all the related `InternalNamePath[]`.
* a <- b <- c : change `a`
* relatedFields=[a, b, c]
*/
relatedFields: InternalNamePath[];
}
export type NotifyInfo = ValueUpdateInfo | ValidateFinishInfo | ResetInfo | RemoveInfo | SetFieldInfo | DependenciesUpdateInfo;
export type ValuedNotifyInfo = NotifyInfo & {
store: Store;
};
export interface Callbacks<Values = any> {
onValuesChange?: (changedValues: any, values: Values) => void;
onFieldsChange?: (changedFields: FieldData[], allFields: FieldData[]) => void;
onFinish?: (values: Values) => void;
onFinishFailed?: (errorInfo: ValidateErrorEntity<Values>) => void;
}
export type WatchCallBack = (values: Store, allValues: Store, namePathList: InternalNamePath[]) => void;
export interface WatchOptions<Form extends FormInstance = FormInstance> {
form?: Form;
preserve?: boolean;
}
export interface InternalHooks {
dispatch: (action: ReducerAction) => void;
initEntityValue: (entity: FieldEntity) => void;
registerField: (entity: FieldEntity) => () => void;
useSubscribe: (subscribable: boolean) => void;
setInitialValues: (values: Store, init: boolean) => void;
destroyForm: (clearOnDestroy?: boolean) => void;
setCallbacks: (callbacks: Callbacks) => void;
registerWatch: (callback: WatchCallBack) => () => void;
getFields: (namePathList?: InternalNamePath[]) => FieldData[];
setValidateMessages: (validateMessages: ValidateMessages) => void;
setPreserve: (preserve?: boolean) => void;
getInitialValue: (namePath: InternalNamePath) => StoreValue;
}
/** Only return partial when type is not any */
type RecursivePartial<T> = NonNullable<T> extends object ? {
[P in keyof T]?: NonNullable<T[P]> extends (infer U)[] ? RecursivePartial<U>[] : NonNullable<T[P]> extends object ? RecursivePartial<T[P]> : T[P];
} : T;
export type FilterFunc = (meta: Meta) => boolean;
export type GetFieldsValueConfig = {
strict?: boolean;
filter?: FilterFunc;
};
export interface FormInstance<Values = any> {
getFieldValue: (name: NamePath<Values>) => StoreValue;
getFieldsValue: (() => Values) & ((nameList: NamePath<Values>[] | true, filterFunc?: FilterFunc) => any) & ((config: GetFieldsValueConfig) => any);
getFieldError: (name: NamePath<Values>) => string[];
getFieldsError: (nameList?: NamePath<Values>[]) => FieldError[];
getFieldWarning: (name: NamePath<Values>) => string[];
isFieldsTouched: ((nameList?: NamePath<Values>[], allFieldsTouched?: boolean) => boolean) & ((allFieldsTouched?: boolean) => boolean);
isFieldTouched: (name: NamePath<Values>) => boolean;
isFieldValidating: (name: NamePath<Values>) => boolean;
isFieldsValidating: (nameList?: NamePath<Values>[]) => boolean;
resetFields: (fields?: NamePath<Values>[]) => void;
setFields: (fields: FieldData<Values>[]) => void;
setFieldValue: (name: NamePath<Values>, value: any) => void;
setFieldsValue: (values: RecursivePartial<Values>) => void;
validateFields: ValidateFields<Values>;
submit: () => void;
}
export type FormRef<Values = any> = FormInstance<Values> & {
nativeElement?: HTMLElement;
};
export type InternalFormInstance = Omit<FormInstance, 'validateFields'> & {
validateFields: InternalValidateFields;
/**
* Passed by field context props
*/
prefixName?: InternalNamePath;
validateTrigger?: string | string[] | false;
/**
* Form component should register some content into store.
* We pass the `HOOK_MARK` as key to avoid user call the function.
*/
getInternalHooks: (secret: string) => InternalHooks | null;
/** @private Internal usage. Do not use it in your production */
_init?: boolean;
};
export type EventArgs = any[];
type ValidateMessage = string | (() => string);
export interface ValidateMessages {
default?: ValidateMessage;
required?: ValidateMessage;
enum?: ValidateMessage;
whitespace?: ValidateMessage;
date?: {
format?: ValidateMessage;
parse?: ValidateMessage;
invalid?: ValidateMessage;
};
types?: {
string?: ValidateMessage;
method?: ValidateMessage;
array?: ValidateMessage;
object?: ValidateMessage;
number?: ValidateMessage;
date?: ValidateMessage;
boolean?: ValidateMessage;
integer?: ValidateMessage;
float?: ValidateMessage;
regexp?: ValidateMessage;
email?: ValidateMessage;
url?: ValidateMessage;
hex?: ValidateMessage;
};
string?: {
len?: ValidateMessage;
min?: ValidateMessage;
max?: ValidateMessage;
range?: ValidateMessage;
};
number?: {
len?: ValidateMessage;
min?: ValidateMessage;
max?: ValidateMessage;
range?: ValidateMessage;
};
array?: {
len?: ValidateMessage;
min?: ValidateMessage;
max?: ValidateMessage;
range?: ValidateMessage;
};
pattern?: {
mismatch?: ValidateMessage;
};
}
export {};

1
node_modules/rc-field-form/es/interface.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

13
node_modules/rc-field-form/es/namePathType.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
type BaseNamePath = string | number | boolean | (string | number | boolean)[];
/**
* Store: The store type from `FormInstance<Store>`
* ParentNamePath: Auto generate by nest logic. Do not fill manually.
*/
export type DeepNamePath<Store = any, ParentNamePath extends any[] = []> = ParentNamePath['length'] extends 5 ? never : true extends (Store extends BaseNamePath ? true : false) ? ParentNamePath['length'] extends 0 ? Store | BaseNamePath : Store extends any[] ? [...ParentNamePath, number] : never : Store extends any[] ? // Connect path. e.g. { a: { b: string }[] }
[
...ParentNamePath,
number
] | DeepNamePath<Store[number], [...ParentNamePath, number]> : keyof Store extends never ? Store : {
[FieldKey in keyof Store]: Store[FieldKey] extends Function ? never : (ParentNamePath['length'] extends 0 ? FieldKey : never) | [...ParentNamePath, FieldKey] | DeepNamePath<Required<Store>[FieldKey], [...ParentNamePath, FieldKey]>;
}[keyof Store];
export {};

1
node_modules/rc-field-form/es/namePathType.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

94
node_modules/rc-field-form/es/useForm.d.ts generated vendored Normal file
View File

@@ -0,0 +1,94 @@
import type { FormInstance, InternalFormInstance, InternalNamePath, StoreValue } from './interface';
interface UpdateAction {
type: 'updateValue';
namePath: InternalNamePath;
value: StoreValue;
}
interface ValidateAction {
type: 'validateField';
namePath: InternalNamePath;
triggerName: string;
}
export type ReducerAction = UpdateAction | ValidateAction;
export declare class FormStore {
private formHooked;
private forceRootUpdate;
private subscribable;
private store;
private fieldEntities;
private initialValues;
private callbacks;
private validateMessages;
private preserve?;
private lastValidatePromise;
constructor(forceRootUpdate: () => void);
getForm: () => InternalFormInstance;
private getInternalHooks;
private useSubscribe;
/**
* Record prev Form unmount fieldEntities which config preserve false.
* This need to be refill with initialValues instead of store value.
*/
private prevWithoutPreserves;
/**
* First time `setInitialValues` should update store with initial value
*/
private setInitialValues;
private destroyForm;
private getInitialValue;
private setCallbacks;
private setValidateMessages;
private setPreserve;
private watchList;
private registerWatch;
private notifyWatch;
private timeoutId;
private warningUnhooked;
private updateStore;
/**
* Get registered field entities.
* @param pure Only return field which has a `name`. Default: false
*/
private getFieldEntities;
private getFieldsMap;
private getFieldEntitiesForNamePathList;
private getFieldsValue;
private getFieldValue;
private getFieldsError;
private getFieldError;
private getFieldWarning;
private isFieldsTouched;
private isFieldTouched;
private isFieldsValidating;
private isFieldValidating;
/**
* Reset Field with field `initialValue` prop.
* Can pass `entities` or `namePathList` or just nothing.
*/
private resetWithFieldInitialValue;
private resetFields;
private setFields;
private getFields;
/**
* This only trigger when a field is on constructor to avoid we get initialValue too late
*/
private initEntityValue;
private isMergedPreserve;
private registerField;
private dispatch;
private notifyObservers;
/**
* Notify dependencies children with parent update
* We need delay to trigger validate in case Field is under render props
*/
private triggerDependenciesUpdate;
private updateValue;
private setFieldsValue;
private setFieldValue;
private getDependencyChildrenFields;
private triggerOnFieldsChange;
private validateFields;
private submit;
}
declare function useForm<Values = any>(form?: FormInstance<Values>): [FormInstance<Values>];
export default useForm;

897
node_modules/rc-field-form/es/useForm.js generated vendored Normal file
View File

@@ -0,0 +1,897 @@
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _typeof from "@babel/runtime/helpers/esm/typeof";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
var _excluded = ["name"];
import { merge } from "rc-util/es/utils/set";
import warning from "rc-util/es/warning";
import * as React from 'react';
import { HOOK_MARK } from "./FieldContext";
import { allPromiseFinish } from "./utils/asyncUtil";
import { defaultValidateMessages } from "./utils/messages";
import NameMap from "./utils/NameMap";
import { cloneByNamePathList, containsNamePath, getNamePath, getValue, matchNamePath, setValue } from "./utils/valueUtil";
export var FormStore = /*#__PURE__*/_createClass(function FormStore(forceRootUpdate) {
var _this = this;
_classCallCheck(this, FormStore);
_defineProperty(this, "formHooked", false);
_defineProperty(this, "forceRootUpdate", void 0);
_defineProperty(this, "subscribable", true);
_defineProperty(this, "store", {});
_defineProperty(this, "fieldEntities", []);
_defineProperty(this, "initialValues", {});
_defineProperty(this, "callbacks", {});
_defineProperty(this, "validateMessages", null);
_defineProperty(this, "preserve", null);
_defineProperty(this, "lastValidatePromise", null);
_defineProperty(this, "getForm", function () {
return {
getFieldValue: _this.getFieldValue,
getFieldsValue: _this.getFieldsValue,
getFieldError: _this.getFieldError,
getFieldWarning: _this.getFieldWarning,
getFieldsError: _this.getFieldsError,
isFieldsTouched: _this.isFieldsTouched,
isFieldTouched: _this.isFieldTouched,
isFieldValidating: _this.isFieldValidating,
isFieldsValidating: _this.isFieldsValidating,
resetFields: _this.resetFields,
setFields: _this.setFields,
setFieldValue: _this.setFieldValue,
setFieldsValue: _this.setFieldsValue,
validateFields: _this.validateFields,
submit: _this.submit,
_init: true,
getInternalHooks: _this.getInternalHooks
};
});
// ======================== Internal Hooks ========================
_defineProperty(this, "getInternalHooks", function (key) {
if (key === HOOK_MARK) {
_this.formHooked = true;
return {
dispatch: _this.dispatch,
initEntityValue: _this.initEntityValue,
registerField: _this.registerField,
useSubscribe: _this.useSubscribe,
setInitialValues: _this.setInitialValues,
destroyForm: _this.destroyForm,
setCallbacks: _this.setCallbacks,
setValidateMessages: _this.setValidateMessages,
getFields: _this.getFields,
setPreserve: _this.setPreserve,
getInitialValue: _this.getInitialValue,
registerWatch: _this.registerWatch
};
}
warning(false, '`getInternalHooks` is internal usage. Should not call directly.');
return null;
});
_defineProperty(this, "useSubscribe", function (subscribable) {
_this.subscribable = subscribable;
});
/**
* Record prev Form unmount fieldEntities which config preserve false.
* This need to be refill with initialValues instead of store value.
*/
_defineProperty(this, "prevWithoutPreserves", null);
/**
* First time `setInitialValues` should update store with initial value
*/
_defineProperty(this, "setInitialValues", function (initialValues, init) {
_this.initialValues = initialValues || {};
if (init) {
var _this$prevWithoutPres;
var nextStore = merge(initialValues, _this.store);
// We will take consider prev form unmount fields.
// When the field is not `preserve`, we need fill this with initialValues instead of store.
// eslint-disable-next-line array-callback-return
(_this$prevWithoutPres = _this.prevWithoutPreserves) === null || _this$prevWithoutPres === void 0 || _this$prevWithoutPres.map(function (_ref) {
var namePath = _ref.key;
nextStore = setValue(nextStore, namePath, getValue(initialValues, namePath));
});
_this.prevWithoutPreserves = null;
_this.updateStore(nextStore);
}
});
_defineProperty(this, "destroyForm", function (clearOnDestroy) {
if (clearOnDestroy) {
// destroy form reset store
_this.updateStore({});
} else {
// Fill preserve fields
var prevWithoutPreserves = new NameMap();
_this.getFieldEntities(true).forEach(function (entity) {
if (!_this.isMergedPreserve(entity.isPreserve())) {
prevWithoutPreserves.set(entity.getNamePath(), true);
}
});
_this.prevWithoutPreserves = prevWithoutPreserves;
}
});
_defineProperty(this, "getInitialValue", function (namePath) {
var initValue = getValue(_this.initialValues, namePath);
// Not cloneDeep when without `namePath`
return namePath.length ? merge(initValue) : initValue;
});
_defineProperty(this, "setCallbacks", function (callbacks) {
_this.callbacks = callbacks;
});
_defineProperty(this, "setValidateMessages", function (validateMessages) {
_this.validateMessages = validateMessages;
});
_defineProperty(this, "setPreserve", function (preserve) {
_this.preserve = preserve;
});
// ============================= Watch ============================
_defineProperty(this, "watchList", []);
_defineProperty(this, "registerWatch", function (callback) {
_this.watchList.push(callback);
return function () {
_this.watchList = _this.watchList.filter(function (fn) {
return fn !== callback;
});
};
});
_defineProperty(this, "notifyWatch", function () {
var namePath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
// No need to cost perf when nothing need to watch
if (_this.watchList.length) {
var values = _this.getFieldsValue();
var allValues = _this.getFieldsValue(true);
_this.watchList.forEach(function (callback) {
callback(values, allValues, namePath);
});
}
});
// ========================== Dev Warning =========================
_defineProperty(this, "timeoutId", null);
_defineProperty(this, "warningUnhooked", function () {
if (process.env.NODE_ENV !== 'production' && !_this.timeoutId && typeof window !== 'undefined') {
_this.timeoutId = setTimeout(function () {
_this.timeoutId = null;
if (!_this.formHooked) {
warning(false, 'Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?');
}
});
}
});
// ============================ Store =============================
_defineProperty(this, "updateStore", function (nextStore) {
_this.store = nextStore;
});
// ============================ Fields ============================
/**
* Get registered field entities.
* @param pure Only return field which has a `name`. Default: false
*/
_defineProperty(this, "getFieldEntities", function () {
var pure = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!pure) {
return _this.fieldEntities;
}
return _this.fieldEntities.filter(function (field) {
return field.getNamePath().length;
});
});
_defineProperty(this, "getFieldsMap", function () {
var pure = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var cache = new NameMap();
_this.getFieldEntities(pure).forEach(function (field) {
var namePath = field.getNamePath();
cache.set(namePath, field);
});
return cache;
});
_defineProperty(this, "getFieldEntitiesForNamePathList", function (nameList) {
if (!nameList) {
return _this.getFieldEntities(true);
}
var cache = _this.getFieldsMap(true);
return nameList.map(function (name) {
var namePath = getNamePath(name);
return cache.get(namePath) || {
INVALIDATE_NAME_PATH: getNamePath(name)
};
});
});
_defineProperty(this, "getFieldsValue", function (nameList, filterFunc) {
_this.warningUnhooked();
// Fill args
var mergedNameList;
var mergedFilterFunc;
var mergedStrict;
if (nameList === true || Array.isArray(nameList)) {
mergedNameList = nameList;
mergedFilterFunc = filterFunc;
} else if (nameList && _typeof(nameList) === 'object') {
mergedStrict = nameList.strict;
mergedFilterFunc = nameList.filter;
}
if (mergedNameList === true && !mergedFilterFunc) {
return _this.store;
}
var fieldEntities = _this.getFieldEntitiesForNamePathList(Array.isArray(mergedNameList) ? mergedNameList : null);
var filteredNameList = [];
fieldEntities.forEach(function (entity) {
var _isListField, _ref3;
var 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 (mergedStrict) {
var _isList, _ref2;
if ((_isList = (_ref2 = entity).isList) !== null && _isList !== void 0 && _isList.call(_ref2)) {
return;
}
} else if (!mergedNameList && (_isListField = (_ref3 = entity).isListField) !== null && _isListField !== void 0 && _isListField.call(_ref3)) {
return;
}
if (!mergedFilterFunc) {
filteredNameList.push(namePath);
} else {
var meta = 'getMeta' in entity ? entity.getMeta() : null;
if (mergedFilterFunc(meta)) {
filteredNameList.push(namePath);
}
}
});
return cloneByNamePathList(_this.store, filteredNameList.map(getNamePath));
});
_defineProperty(this, "getFieldValue", function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
return getValue(_this.store, namePath);
});
_defineProperty(this, "getFieldsError", function (nameList) {
_this.warningUnhooked();
var fieldEntities = _this.getFieldEntitiesForNamePathList(nameList);
return fieldEntities.map(function (entity, index) {
if (entity && !('INVALIDATE_NAME_PATH' in entity)) {
return {
name: entity.getNamePath(),
errors: entity.getErrors(),
warnings: entity.getWarnings()
};
}
return {
name: getNamePath(nameList[index]),
errors: [],
warnings: []
};
});
});
_defineProperty(this, "getFieldError", function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
var fieldError = _this.getFieldsError([namePath])[0];
return fieldError.errors;
});
_defineProperty(this, "getFieldWarning", function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
var fieldError = _this.getFieldsError([namePath])[0];
return fieldError.warnings;
});
_defineProperty(this, "isFieldsTouched", function () {
_this.warningUnhooked();
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var arg0 = args[0],
arg1 = args[1];
var namePathList;
var isAllFieldsTouched = false;
if (args.length === 0) {
namePathList = null;
} else if (args.length === 1) {
if (Array.isArray(arg0)) {
namePathList = arg0.map(getNamePath);
isAllFieldsTouched = false;
} else {
namePathList = null;
isAllFieldsTouched = arg0;
}
} else {
namePathList = arg0.map(getNamePath);
isAllFieldsTouched = arg1;
}
var fieldEntities = _this.getFieldEntities(true);
var isFieldTouched = function isFieldTouched(field) {
return field.isFieldTouched();
};
// ===== Will get fully compare when not config namePathList =====
if (!namePathList) {
return isAllFieldsTouched ? fieldEntities.every(function (entity) {
return isFieldTouched(entity) || entity.isList();
}) : fieldEntities.some(isFieldTouched);
}
// Generate a nest tree for validate
var map = new NameMap();
namePathList.forEach(function (shortNamePath) {
map.set(shortNamePath, []);
});
fieldEntities.forEach(function (field) {
var fieldNamePath = field.getNamePath();
// Find matched entity and put into list
namePathList.forEach(function (shortNamePath) {
if (shortNamePath.every(function (nameUnit, i) {
return fieldNamePath[i] === nameUnit;
})) {
map.update(shortNamePath, function (list) {
return [].concat(_toConsumableArray(list), [field]);
});
}
});
});
// Check if NameMap value is touched
var isNamePathListTouched = function isNamePathListTouched(entities) {
return entities.some(isFieldTouched);
};
var namePathListEntities = map.map(function (_ref4) {
var value = _ref4.value;
return value;
});
return isAllFieldsTouched ? namePathListEntities.every(isNamePathListTouched) : namePathListEntities.some(isNamePathListTouched);
});
_defineProperty(this, "isFieldTouched", function (name) {
_this.warningUnhooked();
return _this.isFieldsTouched([name]);
});
_defineProperty(this, "isFieldsValidating", function (nameList) {
_this.warningUnhooked();
var fieldEntities = _this.getFieldEntities();
if (!nameList) {
return fieldEntities.some(function (testField) {
return testField.isFieldValidating();
});
}
var namePathList = nameList.map(getNamePath);
return fieldEntities.some(function (testField) {
var fieldNamePath = testField.getNamePath();
return containsNamePath(namePathList, fieldNamePath) && testField.isFieldValidating();
});
});
_defineProperty(this, "isFieldValidating", function (name) {
_this.warningUnhooked();
return _this.isFieldsValidating([name]);
});
/**
* Reset Field with field `initialValue` prop.
* Can pass `entities` or `namePathList` or just nothing.
*/
_defineProperty(this, "resetWithFieldInitialValue", function () {
var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// Create cache
var cache = new NameMap();
var fieldEntities = _this.getFieldEntities(true);
fieldEntities.forEach(function (field) {
var initialValue = field.props.initialValue;
var namePath = field.getNamePath();
// Record only if has `initialValue`
if (initialValue !== undefined) {
var records = cache.get(namePath) || new Set();
records.add({
entity: field,
value: initialValue
});
cache.set(namePath, records);
}
});
// Reset
var resetWithFields = function resetWithFields(entities) {
entities.forEach(function (field) {
var initialValue = field.props.initialValue;
if (initialValue !== undefined) {
var namePath = field.getNamePath();
var formInitialValue = _this.getInitialValue(namePath);
if (formInitialValue !== undefined) {
// Warning if conflict with form initialValues and do not modify value
warning(false, "Form already set 'initialValues' with path '".concat(namePath.join('.'), "'. Field can not overwrite it."));
} else {
var records = cache.get(namePath);
if (records && records.size > 1) {
// Warning if multiple field set `initialValue`and do not modify value
warning(false, "Multiple Field with path '".concat(namePath.join('.'), "' set 'initialValue'. Can not decide which one to pick."));
} else if (records) {
var originValue = _this.getFieldValue(namePath);
var isListField = field.isListField();
// Set `initialValue`
if (!isListField && (!info.skipExist || originValue === undefined)) {
_this.updateStore(setValue(_this.store, namePath, _toConsumableArray(records)[0].value));
}
}
}
}
});
};
var requiredFieldEntities;
if (info.entities) {
requiredFieldEntities = info.entities;
} else if (info.namePathList) {
requiredFieldEntities = [];
info.namePathList.forEach(function (namePath) {
var records = cache.get(namePath);
if (records) {
var _requiredFieldEntitie;
(_requiredFieldEntitie = requiredFieldEntities).push.apply(_requiredFieldEntitie, _toConsumableArray(_toConsumableArray(records).map(function (r) {
return r.entity;
})));
}
});
} else {
requiredFieldEntities = fieldEntities;
}
resetWithFields(requiredFieldEntities);
});
_defineProperty(this, "resetFields", function (nameList) {
_this.warningUnhooked();
var prevStore = _this.store;
if (!nameList) {
_this.updateStore(merge(_this.initialValues));
_this.resetWithFieldInitialValue();
_this.notifyObservers(prevStore, null, {
type: 'reset'
});
_this.notifyWatch();
return;
}
// Reset by `nameList`
var namePathList = nameList.map(getNamePath);
namePathList.forEach(function (namePath) {
var initialValue = _this.getInitialValue(namePath);
_this.updateStore(setValue(_this.store, namePath, initialValue));
});
_this.resetWithFieldInitialValue({
namePathList: namePathList
});
_this.notifyObservers(prevStore, namePathList, {
type: 'reset'
});
_this.notifyWatch(namePathList);
});
_defineProperty(this, "setFields", function (fields) {
_this.warningUnhooked();
var prevStore = _this.store;
var namePathList = [];
fields.forEach(function (fieldData) {
var name = fieldData.name,
data = _objectWithoutProperties(fieldData, _excluded);
var namePath = getNamePath(name);
namePathList.push(namePath);
// Value
if ('value' in data) {
_this.updateStore(setValue(_this.store, namePath, data.value));
}
_this.notifyObservers(prevStore, [namePath], {
type: 'setField',
data: fieldData
});
});
_this.notifyWatch(namePathList);
});
_defineProperty(this, "getFields", function () {
var entities = _this.getFieldEntities(true);
var fields = entities.map(function (field) {
var namePath = field.getNamePath();
var meta = field.getMeta();
var fieldData = _objectSpread(_objectSpread({}, meta), {}, {
name: namePath,
value: _this.getFieldValue(namePath)
});
Object.defineProperty(fieldData, 'originRCField', {
value: true
});
return fieldData;
});
return fields;
});
// =========================== Observer ===========================
/**
* This only trigger when a field is on constructor to avoid we get initialValue too late
*/
_defineProperty(this, "initEntityValue", function (entity) {
var initialValue = entity.props.initialValue;
if (initialValue !== undefined) {
var namePath = entity.getNamePath();
var prevValue = getValue(_this.store, namePath);
if (prevValue === undefined) {
_this.updateStore(setValue(_this.store, namePath, initialValue));
}
}
});
_defineProperty(this, "isMergedPreserve", function (fieldPreserve) {
var mergedPreserve = fieldPreserve !== undefined ? fieldPreserve : _this.preserve;
return mergedPreserve !== null && mergedPreserve !== void 0 ? mergedPreserve : true;
});
_defineProperty(this, "registerField", function (entity) {
_this.fieldEntities.push(entity);
var namePath = entity.getNamePath();
_this.notifyWatch([namePath]);
// Set initial values
if (entity.props.initialValue !== undefined) {
var prevStore = _this.store;
_this.resetWithFieldInitialValue({
entities: [entity],
skipExist: true
});
_this.notifyObservers(prevStore, [entity.getNamePath()], {
type: 'valueUpdate',
source: 'internal'
});
}
// un-register field callback
return function (isListField, preserve) {
var subNamePath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
_this.fieldEntities = _this.fieldEntities.filter(function (item) {
return item !== entity;
});
// Clean up store value if not preserve
if (!_this.isMergedPreserve(preserve) && (!isListField || subNamePath.length > 1)) {
var defaultValue = isListField ? undefined : _this.getInitialValue(namePath);
if (namePath.length && _this.getFieldValue(namePath) !== defaultValue && _this.fieldEntities.every(function (field) {
return (
// Only reset when no namePath exist
!matchNamePath(field.getNamePath(), namePath)
);
})) {
var _prevStore = _this.store;
_this.updateStore(setValue(_prevStore, namePath, defaultValue, true));
// Notify that field is unmount
_this.notifyObservers(_prevStore, [namePath], {
type: 'remove'
});
// Dependencies update
_this.triggerDependenciesUpdate(_prevStore, namePath);
}
}
_this.notifyWatch([namePath]);
};
});
_defineProperty(this, "dispatch", function (action) {
switch (action.type) {
case 'updateValue':
{
var namePath = action.namePath,
value = action.value;
_this.updateValue(namePath, value);
break;
}
case 'validateField':
{
var _namePath = action.namePath,
triggerName = action.triggerName;
_this.validateFields([_namePath], {
triggerName: triggerName
});
break;
}
default:
// Currently we don't have other action. Do nothing.
}
});
_defineProperty(this, "notifyObservers", function (prevStore, namePathList, info) {
if (_this.subscribable) {
var mergedInfo = _objectSpread(_objectSpread({}, info), {}, {
store: _this.getFieldsValue(true)
});
_this.getFieldEntities().forEach(function (_ref5) {
var onStoreChange = _ref5.onStoreChange;
onStoreChange(prevStore, namePathList, mergedInfo);
});
} else {
_this.forceRootUpdate();
}
});
/**
* Notify dependencies children with parent update
* We need delay to trigger validate in case Field is under render props
*/
_defineProperty(this, "triggerDependenciesUpdate", function (prevStore, namePath) {
var childrenFields = _this.getDependencyChildrenFields(namePath);
if (childrenFields.length) {
_this.validateFields(childrenFields);
}
_this.notifyObservers(prevStore, childrenFields, {
type: 'dependenciesUpdate',
relatedFields: [namePath].concat(_toConsumableArray(childrenFields))
});
return childrenFields;
});
_defineProperty(this, "updateValue", function (name, value) {
var namePath = getNamePath(name);
var prevStore = _this.store;
_this.updateStore(setValue(_this.store, namePath, value));
_this.notifyObservers(prevStore, [namePath], {
type: 'valueUpdate',
source: 'internal'
});
_this.notifyWatch([namePath]);
// Dependencies update
var childrenFields = _this.triggerDependenciesUpdate(prevStore, namePath);
// trigger callback function
var onValuesChange = _this.callbacks.onValuesChange;
if (onValuesChange) {
var changedValues = cloneByNamePathList(_this.store, [namePath]);
onValuesChange(changedValues, _this.getFieldsValue());
}
_this.triggerOnFieldsChange([namePath].concat(_toConsumableArray(childrenFields)));
});
// Let all child Field get update.
_defineProperty(this, "setFieldsValue", function (store) {
_this.warningUnhooked();
var prevStore = _this.store;
if (store) {
var nextStore = merge(_this.store, store);
_this.updateStore(nextStore);
}
_this.notifyObservers(prevStore, null, {
type: 'valueUpdate',
source: 'external'
});
_this.notifyWatch();
});
_defineProperty(this, "setFieldValue", function (name, value) {
_this.setFields([{
name: name,
value: value,
errors: [],
warnings: []
}]);
});
_defineProperty(this, "getDependencyChildrenFields", function (rootNamePath) {
var children = new Set();
var childrenFields = [];
var dependencies2fields = new NameMap();
/**
* Generate maps
* Can use cache to save perf if user report performance issue with this
*/
_this.getFieldEntities().forEach(function (field) {
var dependencies = field.props.dependencies;
(dependencies || []).forEach(function (dependency) {
var dependencyNamePath = getNamePath(dependency);
dependencies2fields.update(dependencyNamePath, function () {
var fields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Set();
fields.add(field);
return fields;
});
});
});
var fillChildren = function fillChildren(namePath) {
var fields = dependencies2fields.get(namePath) || new Set();
fields.forEach(function (field) {
if (!children.has(field)) {
children.add(field);
var fieldNamePath = field.getNamePath();
if (field.isFieldDirty() && fieldNamePath.length) {
childrenFields.push(fieldNamePath);
fillChildren(fieldNamePath);
}
}
});
};
fillChildren(rootNamePath);
return childrenFields;
});
_defineProperty(this, "triggerOnFieldsChange", function (namePathList, filedErrors) {
var onFieldsChange = _this.callbacks.onFieldsChange;
if (onFieldsChange) {
var fields = _this.getFields();
/**
* Fill errors since `fields` may be replaced by controlled fields
*/
if (filedErrors) {
var cache = new NameMap();
filedErrors.forEach(function (_ref6) {
var name = _ref6.name,
errors = _ref6.errors;
cache.set(name, errors);
});
fields.forEach(function (field) {
// eslint-disable-next-line no-param-reassign
field.errors = cache.get(field.name) || field.errors;
});
}
var changedFields = fields.filter(function (_ref7) {
var fieldName = _ref7.name;
return containsNamePath(namePathList, fieldName);
});
if (changedFields.length) {
onFieldsChange(changedFields, fields);
}
}
});
// =========================== Validate ===========================
_defineProperty(this, "validateFields", function (arg1, arg2) {
_this.warningUnhooked();
var nameList;
var options;
if (Array.isArray(arg1) || typeof arg1 === 'string' || typeof arg2 === 'string') {
nameList = arg1;
options = arg2;
} else {
options = arg1;
}
var provideNameList = !!nameList;
var namePathList = provideNameList ? nameList.map(getNamePath) : [];
// Collect result in promise list
var promiseList = [];
// We temp save the path which need trigger for `onFieldsChange`
var TMP_SPLIT = String(Date.now());
var validateNamePathList = new Set();
var _ref8 = options || {},
recursive = _ref8.recursive,
dirty = _ref8.dirty;
_this.getFieldEntities(true).forEach(function (field) {
// Add field if not provide `nameList`
if (!provideNameList) {
namePathList.push(field.getNamePath());
}
// Skip if without rule
if (!field.props.rules || !field.props.rules.length) {
return;
}
// Skip if only validate dirty field
if (dirty && !field.isFieldDirty()) {
return;
}
var fieldNamePath = field.getNamePath();
validateNamePathList.add(fieldNamePath.join(TMP_SPLIT));
// Add field validate rule in to promise list
if (!provideNameList || containsNamePath(namePathList, fieldNamePath, recursive)) {
var promise = field.validateRules(_objectSpread({
validateMessages: _objectSpread(_objectSpread({}, defaultValidateMessages), _this.validateMessages)
}, options));
// Wrap promise with field
promiseList.push(promise.then(function () {
return {
name: fieldNamePath,
errors: [],
warnings: []
};
}).catch(function (ruleErrors) {
var _ruleErrors$forEach;
var mergedErrors = [];
var mergedWarnings = [];
(_ruleErrors$forEach = ruleErrors.forEach) === null || _ruleErrors$forEach === void 0 || _ruleErrors$forEach.call(ruleErrors, function (_ref9) {
var warningOnly = _ref9.rule.warningOnly,
errors = _ref9.errors;
if (warningOnly) {
mergedWarnings.push.apply(mergedWarnings, _toConsumableArray(errors));
} else {
mergedErrors.push.apply(mergedErrors, _toConsumableArray(errors));
}
});
if (mergedErrors.length) {
return Promise.reject({
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings
});
}
return {
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings
};
}));
}
});
var summaryPromise = allPromiseFinish(promiseList);
_this.lastValidatePromise = summaryPromise;
// Notify fields with rule that validate has finished and need update
summaryPromise.catch(function (results) {
return results;
}).then(function (results) {
var resultNamePathList = results.map(function (_ref10) {
var name = _ref10.name;
return name;
});
_this.notifyObservers(_this.store, resultNamePathList, {
type: 'validateFinish'
});
_this.triggerOnFieldsChange(resultNamePathList, results);
});
var returnPromise = summaryPromise.then(function () {
if (_this.lastValidatePromise === summaryPromise) {
return Promise.resolve(_this.getFieldsValue(namePathList));
}
return Promise.reject([]);
}).catch(function (results) {
var errorList = results.filter(function (result) {
return result && result.errors.length;
});
return Promise.reject({
values: _this.getFieldsValue(namePathList),
errorFields: errorList,
outOfDate: _this.lastValidatePromise !== summaryPromise
});
});
// Do not throw in console
returnPromise.catch(function (e) {
return e;
});
// `validating` changed. Trigger `onFieldsChange`
var triggerNamePathList = namePathList.filter(function (namePath) {
return validateNamePathList.has(namePath.join(TMP_SPLIT));
});
_this.triggerOnFieldsChange(triggerNamePathList);
return returnPromise;
});
// ============================ Submit ============================
_defineProperty(this, "submit", function () {
_this.warningUnhooked();
_this.validateFields().then(function (values) {
var onFinish = _this.callbacks.onFinish;
if (onFinish) {
try {
onFinish(values);
} catch (err) {
// Should print error if user `onFinish` callback failed
console.error(err);
}
}
}).catch(function (e) {
var onFinishFailed = _this.callbacks.onFinishFailed;
if (onFinishFailed) {
onFinishFailed(e);
}
});
});
this.forceRootUpdate = forceRootUpdate;
});
function useForm(form) {
var formRef = React.useRef();
var _React$useState = React.useState({}),
_React$useState2 = _slicedToArray(_React$useState, 2),
forceUpdate = _React$useState2[1];
if (!formRef.current) {
if (form) {
formRef.current = form;
} else {
// Create a new FormStore if not provided
var forceReRender = function forceReRender() {
forceUpdate({});
};
var formStore = new FormStore(forceReRender);
formRef.current = formStore.getForm();
}
}
return [formRef.current];
}
export default useForm;

14
node_modules/rc-field-form/es/useWatch.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import type { FormInstance, NamePath, Store, WatchOptions } from './interface';
type ReturnPromise<T> = T extends Promise<infer ValueType> ? ValueType : never;
type GetGeneric<TForm extends FormInstance> = ReturnPromise<ReturnType<TForm['validateFields']>>;
export declare function stringify(value: any): string | number;
declare function useWatch<TDependencies1 extends keyof GetGeneric<TForm>, TForm extends FormInstance, TDependencies2 extends keyof GetGeneric<TForm>[TDependencies1], TDependencies3 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2], TDependencies4 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3]>(dependencies: [TDependencies1, TDependencies2, TDependencies3, TDependencies4], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3][TDependencies4];
declare function useWatch<TDependencies1 extends keyof GetGeneric<TForm>, TForm extends FormInstance, TDependencies2 extends keyof GetGeneric<TForm>[TDependencies1], TDependencies3 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2]>(dependencies: [TDependencies1, TDependencies2, TDependencies3], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3];
declare function useWatch<TDependencies1 extends keyof GetGeneric<TForm>, TForm extends FormInstance, TDependencies2 extends keyof GetGeneric<TForm>[TDependencies1]>(dependencies: [TDependencies1, TDependencies2], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies1][TDependencies2];
declare function useWatch<TDependencies extends keyof GetGeneric<TForm>, TForm extends FormInstance>(dependencies: TDependencies | [TDependencies], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies];
declare function useWatch<TForm extends FormInstance>(dependencies: [], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>;
declare function useWatch<TForm extends FormInstance, TSelected = unknown>(selector: (values: GetGeneric<TForm>) => TSelected, form?: TForm | WatchOptions<TForm>): TSelected;
declare function useWatch<ValueType = Store, TSelected = unknown>(selector: (values: ValueType) => TSelected, form?: FormInstance | WatchOptions<FormInstance>): TSelected;
declare function useWatch<TForm extends FormInstance>(dependencies: NamePath, form?: TForm | WatchOptions<TForm>): any;
declare function useWatch<ValueType = Store>(dependencies: NamePath, form?: FormInstance | WatchOptions<FormInstance>): ValueType;
export default useWatch;

95
node_modules/rc-field-form/es/useWatch.js generated vendored Normal file
View File

@@ -0,0 +1,95 @@
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import warning from "rc-util/es/warning";
import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import FieldContext, { HOOK_MARK } from "./FieldContext";
import { isFormInstance } from "./utils/typeUtil";
import { getNamePath, getValue } from "./utils/valueUtil";
export function stringify(value) {
try {
return JSON.stringify(value);
} catch (err) {
return Math.random();
}
}
var useWatchWarning = process.env.NODE_ENV !== 'production' ? function (namePath) {
var fullyStr = namePath.join('__RC_FIELD_FORM_SPLIT__');
var nameStrRef = useRef(fullyStr);
warning(nameStrRef.current === fullyStr, '`useWatch` is not support dynamic `namePath`. Please provide static instead.');
} : function () {};
// ------- selector type -------
// ------- selector type end -------
function useWatch() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var dependencies = args[0],
_args$ = args[1],
_form = _args$ === void 0 ? {} : _args$;
var options = isFormInstance(_form) ? {
form: _form
} : _form;
var form = options.form;
var _useState = useState(),
_useState2 = _slicedToArray(_useState, 2),
value = _useState2[0],
setValue = _useState2[1];
var valueStr = useMemo(function () {
return stringify(value);
}, [value]);
var valueStrRef = useRef(valueStr);
valueStrRef.current = valueStr;
var fieldContext = useContext(FieldContext);
var formInstance = form || fieldContext;
var isValidForm = formInstance && formInstance._init;
// Warning if not exist form instance
if (process.env.NODE_ENV !== 'production') {
warning(args.length === 2 ? form ? isValidForm : true : isValidForm, 'useWatch requires a form instance since it can not auto detect from context.');
}
var namePath = getNamePath(dependencies);
var namePathRef = useRef(namePath);
namePathRef.current = namePath;
useWatchWarning(namePath);
useEffect(function () {
// Skip if not exist form instance
if (!isValidForm) {
return;
}
var getFieldsValue = formInstance.getFieldsValue,
getInternalHooks = formInstance.getInternalHooks;
var _getInternalHooks = getInternalHooks(HOOK_MARK),
registerWatch = _getInternalHooks.registerWatch;
var getWatchValue = function getWatchValue(values, allValues) {
var watchValue = options.preserve ? allValues : values;
return typeof dependencies === 'function' ? dependencies(watchValue) : getValue(watchValue, namePathRef.current);
};
var cancelRegister = registerWatch(function (values, allValues) {
var newValue = getWatchValue(values, allValues);
var nextValueStr = stringify(newValue);
// Compare stringify in case it's nest object
if (valueStrRef.current !== nextValueStr) {
valueStrRef.current = nextValueStr;
setValue(newValue);
}
});
// TODO: We can improve this perf in future
var initialValue = getWatchValue(getFieldsValue(), getFieldsValue(true));
// React 18 has the bug that will queue update twice even the value is not changed
// ref: https://github.com/facebook/react/issues/27213
if (value !== initialValue) {
setValue(initialValue);
}
return cancelRegister;
},
// We do not need re-register since namePath content is the same
// eslint-disable-next-line react-hooks/exhaustive-deps
[isValidForm]);
return value;
}
export default useWatch;

18
node_modules/rc-field-form/es/utils/NameMap.d.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import type { InternalNamePath } from '../interface';
interface KV<T> {
key: InternalNamePath;
value: T;
}
/**
* NameMap like a `Map` but accepts `string[]` as key.
*/
declare class NameMap<T> {
private kvs;
set(key: InternalNamePath, value: T): void;
get(key: InternalNamePath): T;
update(key: InternalNamePath, updater: (origin: T) => T | null): void;
delete(key: InternalNamePath): void;
map<U>(callback: (kv: KV<T>) => U): U[];
toJSON(): Record<string, T>;
}
export default NameMap;

91
node_modules/rc-field-form/es/utils/NameMap.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _typeof from "@babel/runtime/helpers/esm/typeof";
var SPLIT = '__@field_split__';
/**
* Convert name path into string to fast the fetch speed of Map.
*/
function normalize(namePath) {
return namePath.map(function (cell) {
return "".concat(_typeof(cell), ":").concat(cell);
})
// Magic split
.join(SPLIT);
}
/**
* NameMap like a `Map` but accepts `string[]` as key.
*/
var NameMap = /*#__PURE__*/function () {
function NameMap() {
_classCallCheck(this, NameMap);
_defineProperty(this, "kvs", new Map());
}
_createClass(NameMap, [{
key: "set",
value: function set(key, value) {
this.kvs.set(normalize(key), value);
}
}, {
key: "get",
value: function get(key) {
return this.kvs.get(normalize(key));
}
}, {
key: "update",
value: function update(key, updater) {
var origin = this.get(key);
var next = updater(origin);
if (!next) {
this.delete(key);
} else {
this.set(key, next);
}
}
}, {
key: "delete",
value: function _delete(key) {
this.kvs.delete(normalize(key));
}
// Since we only use this in test, let simply realize this
}, {
key: "map",
value: function map(callback) {
return _toConsumableArray(this.kvs.entries()).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
var cells = key.split(SPLIT);
return callback({
key: cells.map(function (cell) {
var _cell$match = cell.match(/^([^:]*):(.*)$/),
_cell$match2 = _slicedToArray(_cell$match, 3),
type = _cell$match2[1],
unit = _cell$match2[2];
return type === 'number' ? Number(unit) : unit;
}),
value: value
});
});
}
}, {
key: "toJSON",
value: function toJSON() {
var json = {};
this.map(function (_ref3) {
var key = _ref3.key,
value = _ref3.value;
json[key.join('.')] = value;
return null;
});
return json;
}
}]);
return NameMap;
}();
export default NameMap;

2
node_modules/rc-field-form/es/utils/asyncUtil.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import type { FieldError } from '../interface';
export declare function allPromiseFinish(promiseList: Promise<FieldError>[]): Promise<FieldError[]>;

26
node_modules/rc-field-form/es/utils/asyncUtil.js generated vendored Normal file
View File

@@ -0,0 +1,26 @@
export function allPromiseFinish(promiseList) {
var hasError = false;
var count = promiseList.length;
var results = [];
if (!promiseList.length) {
return Promise.resolve([]);
}
return new Promise(function (resolve, reject) {
promiseList.forEach(function (promise, index) {
promise.catch(function (e) {
hasError = true;
return e;
}).then(function (result) {
count -= 1;
results[index] = result;
if (count > 0) {
return;
}
if (hasError) {
reject(results);
}
resolve(results);
});
});
});
}

47
node_modules/rc-field-form/es/utils/messages.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
export declare const defaultValidateMessages: {
default: string;
required: string;
enum: string;
whitespace: string;
date: {
format: string;
parse: string;
invalid: string;
};
types: {
string: string;
method: string;
array: string;
object: string;
number: string;
date: string;
boolean: string;
integer: string;
float: string;
regexp: string;
email: string;
url: string;
hex: string;
};
string: {
len: string;
min: string;
max: string;
range: string;
};
number: {
len: string;
min: string;
max: string;
range: string;
};
array: {
len: string;
min: string;
max: string;
range: string;
};
pattern: {
mismatch: string;
};
};

48
node_modules/rc-field-form/es/utils/messages.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
var typeTemplate = "'${name}' is not a valid ${type}";
export var defaultValidateMessages = {
default: "Validation error on field '${name}'",
required: "'${name}' is required",
enum: "'${name}' must be one of [${enum}]",
whitespace: "'${name}' cannot be empty",
date: {
format: "'${name}' is invalid for format date",
parse: "'${name}' could not be parsed as date",
invalid: "'${name}' is invalid date"
},
types: {
string: typeTemplate,
method: typeTemplate,
array: typeTemplate,
object: typeTemplate,
number: typeTemplate,
date: typeTemplate,
boolean: typeTemplate,
integer: typeTemplate,
float: typeTemplate,
regexp: typeTemplate,
email: typeTemplate,
url: typeTemplate,
hex: typeTemplate
},
string: {
len: "'${name}' must be exactly ${len} characters",
min: "'${name}' must be at least ${min} characters",
max: "'${name}' cannot be longer than ${max} characters",
range: "'${name}' must be between ${min} and ${max} characters"
},
number: {
len: "'${name}' must equal ${len}",
min: "'${name}' cannot be less than ${min}",
max: "'${name}' cannot be greater than ${max}",
range: "'${name}' must be between ${min} and ${max}"
},
array: {
len: "'${name}' must be exactly ${len} in length",
min: "'${name}' cannot be less than ${min} in length",
max: "'${name}' cannot be greater than ${max} in length",
range: "'${name}' must be between ${min} and ${max} in length"
},
pattern: {
mismatch: "'${name}' does not match pattern ${pattern}"
}
};

3
node_modules/rc-field-form/es/utils/typeUtil.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { FormInstance } from '../interface';
export declare function toArray<T>(value?: T | T[] | null): T[];
export declare function isFormInstance<T>(form: T | FormInstance): form is FormInstance;

9
node_modules/rc-field-form/es/utils/typeUtil.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
export function toArray(value) {
if (value === undefined || value === null) {
return [];
}
return Array.isArray(value) ? value : [value];
}
export function isFormInstance(form) {
return form && !!form._init;
}

View File

@@ -0,0 +1,6 @@
import type { InternalNamePath, InternalValidateOptions, RuleObject, StoreValue, RuleError } from '../interface';
/**
* We use `async-validator` to validate the value.
* But only check one value in a time to avoid namePath validate issue.
*/
export declare function validateRules(namePath: InternalNamePath, value: StoreValue, rules: RuleObject[], options: InternalValidateOptions, validateFirst: boolean | 'parallel', messageVariables?: Record<string, string>): Promise<RuleError[]>;

313
node_modules/rc-field-form/es/utils/validateUtil.js generated vendored Normal file
View File

@@ -0,0 +1,313 @@
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import RawAsyncValidator from '@rc-component/async-validator';
import * as React from 'react';
import warning from "rc-util/es/warning";
import { defaultValidateMessages } from "./messages";
import { merge } from "rc-util/es/utils/set";
// Remove incorrect original ts define
var AsyncValidator = RawAsyncValidator;
/**
* Replace with template.
* `I'm ${name}` + { name: 'bamboo' } = I'm bamboo
*/
function replaceMessage(template, kv) {
return template.replace(/\\?\$\{\w+\}/g, function (str) {
if (str.startsWith('\\')) {
return str.slice(1);
}
var key = str.slice(2, -1);
return kv[key];
});
}
var CODE_LOGIC_ERROR = 'CODE_LOGIC_ERROR';
function validateRule(_x, _x2, _x3, _x4, _x5) {
return _validateRule.apply(this, arguments);
}
/**
* We use `async-validator` to validate the value.
* But only check one value in a time to avoid namePath validate issue.
*/
function _validateRule() {
_validateRule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(name, value, rule, options, messageVariables) {
var cloneRule, originValidator, subRuleField, validator, messages, result, subResults, kv, fillVariableResult;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
cloneRule = _objectSpread({}, rule); // Bug of `async-validator`
// https://github.com/react-component/field-form/issues/316
// https://github.com/react-component/field-form/issues/313
delete cloneRule.ruleIndex;
// https://github.com/ant-design/ant-design/issues/40497#issuecomment-1422282378
AsyncValidator.warning = function () {
return void 0;
};
if (cloneRule.validator) {
originValidator = cloneRule.validator;
cloneRule.validator = function () {
try {
return originValidator.apply(void 0, arguments);
} catch (error) {
console.error(error);
return Promise.reject(CODE_LOGIC_ERROR);
}
};
}
// We should special handle array validate
subRuleField = null;
if (cloneRule && cloneRule.type === 'array' && cloneRule.defaultField) {
subRuleField = cloneRule.defaultField;
delete cloneRule.defaultField;
}
validator = new AsyncValidator(_defineProperty({}, name, [cloneRule]));
messages = merge(defaultValidateMessages, options.validateMessages);
validator.messages(messages);
result = [];
_context2.prev = 10;
_context2.next = 13;
return Promise.resolve(validator.validate(_defineProperty({}, name, value), _objectSpread({}, options)));
case 13:
_context2.next = 18;
break;
case 15:
_context2.prev = 15;
_context2.t0 = _context2["catch"](10);
if (_context2.t0.errors) {
result = _context2.t0.errors.map(function (_ref4, index) {
var message = _ref4.message;
var mergedMessage = message === CODE_LOGIC_ERROR ? messages.default : message;
return /*#__PURE__*/React.isValidElement(mergedMessage) ?
/*#__PURE__*/
// Wrap ReactNode with `key`
React.cloneElement(mergedMessage, {
key: "error_".concat(index)
}) : mergedMessage;
});
}
case 18:
if (!(!result.length && subRuleField && Array.isArray(value) && value.length > 0)) {
_context2.next = 23;
break;
}
_context2.next = 21;
return Promise.all(value.map(function (subValue, i) {
return validateRule("".concat(name, ".").concat(i), subValue, subRuleField, options, messageVariables);
}));
case 21:
subResults = _context2.sent;
return _context2.abrupt("return", subResults.reduce(function (prev, errors) {
return [].concat(_toConsumableArray(prev), _toConsumableArray(errors));
}, []));
case 23:
// Replace message with variables
kv = _objectSpread(_objectSpread({}, rule), {}, {
name: name,
enum: (rule.enum || []).join(', ')
}, messageVariables);
fillVariableResult = result.map(function (error) {
if (typeof error === 'string') {
return replaceMessage(error, kv);
}
return error;
});
return _context2.abrupt("return", fillVariableResult);
case 26:
case "end":
return _context2.stop();
}
}, _callee2, null, [[10, 15]]);
}));
return _validateRule.apply(this, arguments);
}
export function validateRules(namePath, value, rules, options, validateFirst, messageVariables) {
var name = namePath.join('.');
// Fill rule with context
var filledRules = rules.map(function (currentRule, ruleIndex) {
var originValidatorFunc = currentRule.validator;
var cloneRule = _objectSpread(_objectSpread({}, currentRule), {}, {
ruleIndex: ruleIndex
});
// Replace validator if needed
if (originValidatorFunc) {
cloneRule.validator = function (rule, val, callback) {
var hasPromise = false;
// Wrap callback only accept when promise not provided
var wrappedCallback = function wrappedCallback() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Wait a tick to make sure return type is a promise
Promise.resolve().then(function () {
warning(!hasPromise, 'Your validator function has already return a promise. `callback` will be ignored.');
if (!hasPromise) {
callback.apply(void 0, args);
}
});
};
// Get promise
var promise = originValidatorFunc(rule, val, wrappedCallback);
hasPromise = promise && typeof promise.then === 'function' && typeof promise.catch === 'function';
/**
* 1. Use promise as the first priority.
* 2. If promise not exist, use callback with warning instead
*/
warning(hasPromise, '`callback` is deprecated. Please return a promise instead.');
if (hasPromise) {
promise.then(function () {
callback();
}).catch(function (err) {
callback(err || ' ');
});
}
};
}
return cloneRule;
}).sort(function (_ref, _ref2) {
var w1 = _ref.warningOnly,
i1 = _ref.ruleIndex;
var w2 = _ref2.warningOnly,
i2 = _ref2.ruleIndex;
if (!!w1 === !!w2) {
// Let keep origin order
return i1 - i2;
}
if (w1) {
return 1;
}
return -1;
});
// Do validate rules
var summaryPromise;
if (validateFirst === true) {
// >>>>> Validate by serialization
summaryPromise = new Promise( /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject) {
var i, rule, errors;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
i = 0;
case 1:
if (!(i < filledRules.length)) {
_context.next = 12;
break;
}
rule = filledRules[i];
_context.next = 5;
return validateRule(name, value, rule, options, messageVariables);
case 5:
errors = _context.sent;
if (!errors.length) {
_context.next = 9;
break;
}
reject([{
errors: errors,
rule: rule
}]);
return _context.abrupt("return");
case 9:
i += 1;
_context.next = 1;
break;
case 12:
/* eslint-enable */
resolve([]);
case 13:
case "end":
return _context.stop();
}
}, _callee);
}));
return function (_x6, _x7) {
return _ref3.apply(this, arguments);
};
}());
} else {
// >>>>> Validate by parallel
var rulePromises = filledRules.map(function (rule) {
return validateRule(name, value, rule, options, messageVariables).then(function (errors) {
return {
errors: errors,
rule: rule
};
});
});
summaryPromise = (validateFirst ? finishOnFirstFailed(rulePromises) : finishOnAllFailed(rulePromises)).then(function (errors) {
// Always change to rejection for Field to catch
return Promise.reject(errors);
});
}
// Internal catch error to avoid console error log.
summaryPromise.catch(function (e) {
return e;
});
return summaryPromise;
}
function finishOnAllFailed(_x8) {
return _finishOnAllFailed.apply(this, arguments);
}
function _finishOnAllFailed() {
_finishOnAllFailed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(rulePromises) {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", Promise.all(rulePromises).then(function (errorsList) {
var _ref5;
var errors = (_ref5 = []).concat.apply(_ref5, _toConsumableArray(errorsList));
return errors;
}));
case 1:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return _finishOnAllFailed.apply(this, arguments);
}
function finishOnFirstFailed(_x9) {
return _finishOnFirstFailed.apply(this, arguments);
}
function _finishOnFirstFailed() {
_finishOnFirstFailed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(rulePromises) {
var count;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
count = 0;
return _context4.abrupt("return", new Promise(function (resolve) {
rulePromises.forEach(function (promise) {
promise.then(function (ruleError) {
if (ruleError.errors.length) {
resolve([ruleError]);
}
count += 1;
if (count === rulePromises.length) {
resolve([]);
}
});
});
}));
case 2:
case "end":
return _context4.stop();
}
}, _callee4);
}));
return _finishOnFirstFailed.apply(this, arguments);
}

41
node_modules/rc-field-form/es/utils/valueUtil.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import getValue from 'rc-util/lib/utils/get';
import setValue from 'rc-util/lib/utils/set';
import type { InternalNamePath, NamePath, Store, EventArgs } from '../interface';
export { getValue, setValue };
/**
* Convert name to internal supported format.
* This function should keep since we still thinking if need support like `a.b.c` format.
* 'a' => ['a']
* 123 => [123]
* ['a', 123] => ['a', 123]
*/
export declare function getNamePath(path: NamePath | null): InternalNamePath;
export declare function cloneByNamePathList(store: Store, namePathList: InternalNamePath[]): Store;
/**
* Check if `namePathList` includes `namePath`.
* @param namePathList A list of `InternalNamePath[]`
* @param namePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
export declare function containsNamePath(namePathList: InternalNamePath[], namePath: InternalNamePath, partialMatch?: boolean): boolean;
/**
* Check if `namePath` is super set or equal of `subNamePath`.
* @param namePath A list of `InternalNamePath[]`
* @param subNamePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
export declare function matchNamePath(namePath: InternalNamePath, subNamePath: InternalNamePath | null, partialMatch?: boolean): boolean;
type SimilarObject = string | number | object;
export declare function isSimilar(source: SimilarObject, target: SimilarObject): boolean;
export declare function defaultGetValueFromEvent(valuePropName: string, ...args: EventArgs): any;
/**
* Moves an array item from one position in an array to another.
*
* Note: This is a pure function so a new array will be returned, instead
* of altering the array argument.
*
* @param array Array in which to move an item. (required)
* @param moveIndex The index of the item to move. (required)
* @param toIndex The index to move item at moveIndex to. (required)
*/
export declare function move<T>(array: T[], moveIndex: number, toIndex: number): T[];

117
node_modules/rc-field-form/es/utils/valueUtil.js generated vendored Normal file
View File

@@ -0,0 +1,117 @@
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _typeof from "@babel/runtime/helpers/esm/typeof";
import getValue from "rc-util/es/utils/get";
import setValue from "rc-util/es/utils/set";
import { toArray } from "./typeUtil";
export { getValue, setValue };
/**
* Convert name to internal supported format.
* This function should keep since we still thinking if need support like `a.b.c` format.
* 'a' => ['a']
* 123 => [123]
* ['a', 123] => ['a', 123]
*/
export function getNamePath(path) {
return toArray(path);
}
export function cloneByNamePathList(store, namePathList) {
var newStore = {};
namePathList.forEach(function (namePath) {
var value = getValue(store, namePath);
newStore = setValue(newStore, namePath, value);
});
return newStore;
}
/**
* Check if `namePathList` includes `namePath`.
* @param namePathList A list of `InternalNamePath[]`
* @param namePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
export function containsNamePath(namePathList, namePath) {
var partialMatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return namePathList && namePathList.some(function (path) {
return matchNamePath(namePath, path, partialMatch);
});
}
/**
* Check if `namePath` is super set or equal of `subNamePath`.
* @param namePath A list of `InternalNamePath[]`
* @param subNamePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
export function matchNamePath(namePath, subNamePath) {
var partialMatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!namePath || !subNamePath) {
return false;
}
if (!partialMatch && namePath.length !== subNamePath.length) {
return false;
}
return subNamePath.every(function (nameUnit, i) {
return namePath[i] === nameUnit;
});
}
// Like `shallowEqual`, but we not check the data which may cause re-render
export function isSimilar(source, target) {
if (source === target) {
return true;
}
if (!source && target || source && !target) {
return false;
}
if (!source || !target || _typeof(source) !== 'object' || _typeof(target) !== 'object') {
return false;
}
var sourceKeys = Object.keys(source);
var targetKeys = Object.keys(target);
var keys = new Set([].concat(sourceKeys, targetKeys));
return _toConsumableArray(keys).every(function (key) {
var sourceValue = source[key];
var targetValue = target[key];
if (typeof sourceValue === 'function' && typeof targetValue === 'function') {
return true;
}
return sourceValue === targetValue;
});
}
export function defaultGetValueFromEvent(valuePropName) {
var event = arguments.length <= 1 ? undefined : arguments[1];
if (event && event.target && _typeof(event.target) === 'object' && valuePropName in event.target) {
return event.target[valuePropName];
}
return event;
}
/**
* Moves an array item from one position in an array to another.
*
* Note: This is a pure function so a new array will be returned, instead
* of altering the array argument.
*
* @param array Array in which to move an item. (required)
* @param moveIndex The index of the item to move. (required)
* @param toIndex The index to move item at moveIndex to. (required)
*/
export function move(array, moveIndex, toIndex) {
var length = array.length;
if (moveIndex < 0 || moveIndex >= length || toIndex < 0 || toIndex >= length) {
return array;
}
var item = array[moveIndex];
var diff = moveIndex - toIndex;
if (diff > 0) {
// move left
return [].concat(_toConsumableArray(array.slice(0, toIndex)), [item], _toConsumableArray(array.slice(toIndex, moveIndex)), _toConsumableArray(array.slice(moveIndex + 1, length)));
}
if (diff < 0) {
// move right
return [].concat(_toConsumableArray(array.slice(0, moveIndex)), _toConsumableArray(array.slice(moveIndex + 1, toIndex + 1)), [item], _toConsumableArray(array.slice(toIndex + 1, length)));
}
return array;
}

54
node_modules/rc-field-form/lib/Field.d.ts generated vendored Normal file
View File

@@ -0,0 +1,54 @@
import * as React from 'react';
import type { EventArgs, FormInstance, InternalFormInstance, InternalNamePath, Meta, NamePath, Rule, Store, StoreValue } from './interface';
export type ShouldUpdate<Values = any> = boolean | ((prevValues: Values, nextValues: Values, info: {
source?: string;
}) => boolean);
interface ChildProps {
[name: string]: any;
}
export type MetaEvent = Meta & {
destroy?: boolean;
};
export interface InternalFieldProps<Values = any> {
children?: React.ReactElement | ((control: ChildProps, meta: Meta, form: FormInstance<Values>) => React.ReactNode);
/**
* Set up `dependencies` field.
* When dependencies field update and current field is touched,
* will trigger validate rules and render.
*/
dependencies?: NamePath[];
getValueFromEvent?: (...args: EventArgs) => StoreValue;
name?: InternalNamePath;
normalize?: (value: StoreValue, prevValue: StoreValue, allValues: Store) => StoreValue;
rules?: Rule[];
shouldUpdate?: ShouldUpdate<Values>;
trigger?: string;
validateTrigger?: string | string[] | false;
/**
* Trigger will after configured milliseconds.
*/
validateDebounce?: number;
validateFirst?: boolean | 'parallel';
valuePropName?: string;
getValueProps?: (value: StoreValue) => Record<string, unknown>;
messageVariables?: Record<string, string>;
initialValue?: any;
onReset?: () => void;
onMetaChange?: (meta: MetaEvent) => void;
preserve?: boolean;
/** @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;
}
export interface FieldProps<Values = any> extends Omit<InternalFieldProps<Values>, 'name' | 'fieldContext'> {
name?: NamePath<Values>;
}
export interface FieldState {
resetCount: number;
}
declare function WrapperField<Values = any>({ name, ...restProps }: FieldProps<Values>): React.JSX.Element;
export default WrapperField;

622
node_modules/rc-field-form/lib/Field.js generated vendored Normal file
View File

@@ -0,0 +1,622 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/regeneratorRuntime"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _toArray = _interopRequireDefault(require("rc-util/lib/Children/toArray"));
var _isEqual = _interopRequireDefault(require("rc-util/lib/isEqual"));
var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
var React = _interopRequireWildcard(require("react"));
var _FieldContext = _interopRequireWildcard(require("./FieldContext"));
var _ListContext = _interopRequireDefault(require("./ListContext"));
var _typeUtil = require("./utils/typeUtil");
var _validateUtil = require("./utils/validateUtil");
var _valueUtil = require("./utils/valueUtil");
var _excluded = ["name"];
var EMPTY_ERRORS = [];
function requireUpdate(shouldUpdate, prev, next, prevValue, nextValue, info) {
if (typeof shouldUpdate === 'function') {
return shouldUpdate(prev, next, 'source' in info ? {
source: info.source
} : {});
}
return prevValue !== nextValue;
}
// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
// We use Class instead of Hooks here since it will cost much code by using Hooks.
var Field = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(Field, _React$Component);
var _super = (0, _createSuper2.default)(Field);
// ============================== Subscriptions ==============================
function Field(props) {
var _this;
(0, _classCallCheck2.default)(this, Field);
_this = _super.call(this, props);
// Register on init
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", {
resetCount: 0
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "cancelRegisterFunc", null);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "mounted", false);
/**
* Follow state should not management in State since it will async update by React.
* This makes first render of form can not get correct state value.
*/
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "touched", false);
/**
* Mark when touched & validated. Currently only used for `dependencies`.
* Note that we do not think field with `initialValue` is dirty
* but this will be by `isFieldDirty` func.
*/
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "dirty", false);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "validatePromise", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "prevValidating", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "errors", EMPTY_ERRORS);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "warnings", EMPTY_ERRORS);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "cancelRegister", function () {
var _this$props = _this.props,
preserve = _this$props.preserve,
isListField = _this$props.isListField,
name = _this$props.name;
if (_this.cancelRegisterFunc) {
_this.cancelRegisterFunc(isListField, preserve, (0, _valueUtil.getNamePath)(name));
}
_this.cancelRegisterFunc = null;
});
// ================================== Utils ==================================
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getNamePath", function () {
var _this$props2 = _this.props,
name = _this$props2.name,
fieldContext = _this$props2.fieldContext;
var _fieldContext$prefixN = fieldContext.prefixName,
prefixName = _fieldContext$prefixN === void 0 ? [] : _fieldContext$prefixN;
return name !== undefined ? [].concat((0, _toConsumableArray2.default)(prefixName), (0, _toConsumableArray2.default)(name)) : [];
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getRules", function () {
var _this$props3 = _this.props,
_this$props3$rules = _this$props3.rules,
rules = _this$props3$rules === void 0 ? [] : _this$props3$rules,
fieldContext = _this$props3.fieldContext;
return rules.map(function (rule) {
if (typeof rule === 'function') {
return rule(fieldContext);
}
return rule;
});
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "refresh", function () {
if (!_this.mounted) return;
/**
* Clean up current node.
*/
_this.setState(function (_ref) {
var resetCount = _ref.resetCount;
return {
resetCount: resetCount + 1
};
});
});
// Event should only trigger when meta changed
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "metaCache", null);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "triggerMetaEvent", function (destroy) {
var onMetaChange = _this.props.onMetaChange;
if (onMetaChange) {
var _meta = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _this.getMeta()), {}, {
destroy: destroy
});
if (!(0, _isEqual.default)(_this.metaCache, _meta)) {
onMetaChange(_meta);
}
_this.metaCache = _meta;
} else {
_this.metaCache = null;
}
});
// ========================= Field Entity Interfaces =========================
// Trigger by store update. Check if need update the component
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onStoreChange", function (prevStore, namePathList, info) {
var _this$props4 = _this.props,
shouldUpdate = _this$props4.shouldUpdate,
_this$props4$dependen = _this$props4.dependencies,
dependencies = _this$props4$dependen === void 0 ? [] : _this$props4$dependen,
onReset = _this$props4.onReset;
var store = info.store;
var namePath = _this.getNamePath();
var prevValue = _this.getValue(prevStore);
var curValue = _this.getValue(store);
var namePathMatch = namePathList && (0, _valueUtil.containsNamePath)(namePathList, namePath);
// `setFieldsValue` is a quick access to update related status
if (info.type === 'valueUpdate' && info.source === 'external' && !(0, _isEqual.default)(prevValue, curValue)) {
_this.touched = true;
_this.dirty = true;
_this.validatePromise = null;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
}
switch (info.type) {
case 'reset':
if (!namePathList || namePathMatch) {
// Clean up state
_this.touched = false;
_this.dirty = false;
_this.validatePromise = undefined;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
onReset === null || onReset === void 0 || onReset();
_this.refresh();
return;
}
break;
/**
* In case field with `preserve = false` nest deps like:
* - A = 1 => show B
* - B = 1 => show C
* - Reset A, need clean B, C
*/
case 'remove':
{
if (shouldUpdate && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
case 'setField':
{
var data = info.data;
if (namePathMatch) {
if ('touched' in data) {
_this.touched = data.touched;
}
if ('validating' in data && !('originRCField' in data)) {
_this.validatePromise = data.validating ? Promise.resolve([]) : null;
}
if ('errors' in data) {
_this.errors = data.errors || EMPTY_ERRORS;
}
if ('warnings' in data) {
_this.warnings = data.warnings || EMPTY_ERRORS;
}
_this.dirty = true;
_this.triggerMetaEvent();
_this.reRender();
return;
} else if ('value' in data && (0, _valueUtil.containsNamePath)(namePathList, namePath, true)) {
// Contains path with value should also check
_this.reRender();
return;
}
// Handle update by `setField` with `shouldUpdate`
if (shouldUpdate && !namePath.length && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
case 'dependenciesUpdate':
{
/**
* Trigger when marked `dependencies` updated. Related fields will all update
*/
var dependencyList = dependencies.map(_valueUtil.getNamePath);
// No need for `namePathMath` check and `shouldUpdate` check, since `valueUpdate` will be
// emitted earlier and they will work there
// If set it may cause unnecessary twice rerendering
if (dependencyList.some(function (dependency) {
return (0, _valueUtil.containsNamePath)(info.relatedFields, dependency);
})) {
_this.reRender();
return;
}
break;
}
default:
// 1. If `namePath` exists in `namePathList`, means it's related value and should update
// For example <List name="list"><Field name={['list', 0]}></List>
// If `namePathList` is [['list']] (List value update), Field should be updated
// If `namePathList` is [['list', 0]] (Field value update), List shouldn't be updated
// 2.
// 2.1 If `dependencies` is set, `name` is not set and `shouldUpdate` is not set,
// don't use `shouldUpdate`. `dependencies` is view as a shortcut if `shouldUpdate`
// is not provided
// 2.2 If `shouldUpdate` provided, use customize logic to update the field
// else to check if value changed
if (namePathMatch || (!dependencies.length || namePath.length || shouldUpdate) && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
if (shouldUpdate === true) {
_this.reRender();
}
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "validateRules", function (options) {
// We should fixed namePath & value to avoid developer change then by form function
var namePath = _this.getNamePath();
var currentValue = _this.getValue();
var _ref2 = options || {},
triggerName = _ref2.triggerName,
_ref2$validateOnly = _ref2.validateOnly,
validateOnly = _ref2$validateOnly === void 0 ? false : _ref2$validateOnly;
// Force change to async to avoid rule OOD under renderProps field
var rootPromise = Promise.resolve().then( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee() {
var _this$props5, _this$props5$validate, validateFirst, messageVariables, validateDebounce, filteredRules, promise;
return (0, _regeneratorRuntime2.default)().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (_this.mounted) {
_context.next = 2;
break;
}
return _context.abrupt("return", []);
case 2:
_this$props5 = _this.props, _this$props5$validate = _this$props5.validateFirst, validateFirst = _this$props5$validate === void 0 ? false : _this$props5$validate, messageVariables = _this$props5.messageVariables, validateDebounce = _this$props5.validateDebounce; // Start validate
filteredRules = _this.getRules();
if (triggerName) {
filteredRules = filteredRules.filter(function (rule) {
return rule;
}).filter(function (rule) {
var validateTrigger = rule.validateTrigger;
if (!validateTrigger) {
return true;
}
var triggerList = (0, _typeUtil.toArray)(validateTrigger);
return triggerList.includes(triggerName);
});
}
// Wait for debounce. Skip if no `triggerName` since its from `validateFields / submit`
if (!(validateDebounce && triggerName)) {
_context.next = 10;
break;
}
_context.next = 8;
return new Promise(function (resolve) {
setTimeout(resolve, validateDebounce);
});
case 8:
if (!(_this.validatePromise !== rootPromise)) {
_context.next = 10;
break;
}
return _context.abrupt("return", []);
case 10:
promise = (0, _validateUtil.validateRules)(namePath, currentValue, filteredRules, options, validateFirst, messageVariables);
promise.catch(function (e) {
return e;
}).then(function () {
var ruleErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : EMPTY_ERRORS;
if (_this.validatePromise === rootPromise) {
var _ruleErrors$forEach;
_this.validatePromise = null;
// Get errors & warnings
var nextErrors = [];
var nextWarnings = [];
(_ruleErrors$forEach = ruleErrors.forEach) === null || _ruleErrors$forEach === void 0 || _ruleErrors$forEach.call(ruleErrors, function (_ref4) {
var warningOnly = _ref4.rule.warningOnly,
_ref4$errors = _ref4.errors,
errors = _ref4$errors === void 0 ? EMPTY_ERRORS : _ref4$errors;
if (warningOnly) {
nextWarnings.push.apply(nextWarnings, (0, _toConsumableArray2.default)(errors));
} else {
nextErrors.push.apply(nextErrors, (0, _toConsumableArray2.default)(errors));
}
});
_this.errors = nextErrors;
_this.warnings = nextWarnings;
_this.triggerMetaEvent();
_this.reRender();
}
});
return _context.abrupt("return", promise);
case 13:
case "end":
return _context.stop();
}
}, _callee);
})));
if (validateOnly) {
return rootPromise;
}
_this.validatePromise = rootPromise;
_this.dirty = true;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
// Force trigger re-render since we need sync renderProps with new meta
_this.reRender();
return rootPromise;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isFieldValidating", function () {
return !!_this.validatePromise;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isFieldTouched", function () {
return _this.touched;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isFieldDirty", function () {
// Touched or validate or has initialValue
if (_this.dirty || _this.props.initialValue !== undefined) {
return true;
}
// Form set initialValue
var fieldContext = _this.props.fieldContext;
var _fieldContext$getInte = fieldContext.getInternalHooks(_FieldContext.HOOK_MARK),
getInitialValue = _fieldContext$getInte.getInitialValue;
if (getInitialValue(_this.getNamePath()) !== undefined) {
return true;
}
return false;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getErrors", function () {
return _this.errors;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getWarnings", function () {
return _this.warnings;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isListField", function () {
return _this.props.isListField;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isList", function () {
return _this.props.isList;
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isPreserve", function () {
return _this.props.preserve;
});
// ============================= Child Component =============================
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getMeta", function () {
// Make error & validating in cache to save perf
_this.prevValidating = _this.isFieldValidating();
var meta = {
touched: _this.isFieldTouched(),
validating: _this.prevValidating,
errors: _this.errors,
warnings: _this.warnings,
name: _this.getNamePath(),
validated: _this.validatePromise === null
};
return meta;
});
// Only return validate child node. If invalidate, will do nothing about field.
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getOnlyChild", function (children) {
// Support render props
if (typeof children === 'function') {
var _meta2 = _this.getMeta();
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _this.getOnlyChild(children(_this.getControlled(), _meta2, _this.props.fieldContext))), {}, {
isFunction: true
});
}
// Filed element only
var childList = (0, _toArray.default)(children);
if (childList.length !== 1 || ! /*#__PURE__*/React.isValidElement(childList[0])) {
return {
child: childList,
isFunction: false
};
}
return {
child: childList[0],
isFunction: false
};
});
// ============================== Field Control ==============================
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getValue", function (store) {
var getFieldsValue = _this.props.fieldContext.getFieldsValue;
var namePath = _this.getNamePath();
return (0, _valueUtil.getValue)(store || getFieldsValue(true), namePath);
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getControlled", function () {
var childProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _this$props6 = _this.props,
name = _this$props6.name,
trigger = _this$props6.trigger,
validateTrigger = _this$props6.validateTrigger,
getValueFromEvent = _this$props6.getValueFromEvent,
normalize = _this$props6.normalize,
valuePropName = _this$props6.valuePropName,
getValueProps = _this$props6.getValueProps,
fieldContext = _this$props6.fieldContext;
var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : fieldContext.validateTrigger;
var namePath = _this.getNamePath();
var getInternalHooks = fieldContext.getInternalHooks,
getFieldsValue = fieldContext.getFieldsValue;
var _getInternalHooks = getInternalHooks(_FieldContext.HOOK_MARK),
dispatch = _getInternalHooks.dispatch;
var value = _this.getValue();
var mergedGetValueProps = getValueProps || function (val) {
return (0, _defineProperty2.default)({}, valuePropName, val);
};
var originTriggerFunc = childProps[trigger];
var valueProps = name !== undefined ? mergedGetValueProps(value) : {};
// warning when prop value is function
if (process.env.NODE_ENV !== 'production' && valueProps) {
Object.keys(valueProps).forEach(function (key) {
(0, _warning.default)(typeof valueProps[key] !== 'function', "It's not recommended to generate dynamic function prop by `getValueProps`. Please pass it to child component directly (prop: ".concat(key, ")"));
});
}
var control = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, childProps), valueProps);
// Add trigger
control[trigger] = function () {
// Mark as touched
_this.touched = true;
_this.dirty = true;
_this.triggerMetaEvent();
var newValue;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (getValueFromEvent) {
newValue = getValueFromEvent.apply(void 0, args);
} else {
newValue = _valueUtil.defaultGetValueFromEvent.apply(void 0, [valuePropName].concat(args));
}
if (normalize) {
newValue = normalize(newValue, value, getFieldsValue(true));
}
if (newValue !== value) {
dispatch({
type: 'updateValue',
namePath: namePath,
value: newValue
});
}
if (originTriggerFunc) {
originTriggerFunc.apply(void 0, args);
}
};
// Add validateTrigger
var validateTriggerList = (0, _typeUtil.toArray)(mergedValidateTrigger || []);
validateTriggerList.forEach(function (triggerName) {
// Wrap additional function of component, so that we can get latest value from store
var originTrigger = control[triggerName];
control[triggerName] = function () {
if (originTrigger) {
originTrigger.apply(void 0, arguments);
}
// Always use latest rules
var rules = _this.props.rules;
if (rules && rules.length) {
// We dispatch validate to root,
// since it will update related data with other field with same name
dispatch({
type: 'validateField',
namePath: namePath,
triggerName: triggerName
});
}
};
});
return control;
});
if (props.fieldContext) {
var getInternalHooks = props.fieldContext.getInternalHooks;
var _getInternalHooks2 = getInternalHooks(_FieldContext.HOOK_MARK),
initEntityValue = _getInternalHooks2.initEntityValue;
initEntityValue((0, _assertThisInitialized2.default)(_this));
}
return _this;
}
(0, _createClass2.default)(Field, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this$props7 = this.props,
shouldUpdate = _this$props7.shouldUpdate,
fieldContext = _this$props7.fieldContext;
this.mounted = true;
// Register on init
if (fieldContext) {
var getInternalHooks = fieldContext.getInternalHooks;
var _getInternalHooks3 = getInternalHooks(_FieldContext.HOOK_MARK),
registerField = _getInternalHooks3.registerField;
this.cancelRegisterFunc = registerField(this);
}
// One more render for component in case fields not ready
if (shouldUpdate === true) {
this.reRender();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.cancelRegister();
this.triggerMetaEvent(true);
this.mounted = false;
}
}, {
key: "reRender",
value: function reRender() {
if (!this.mounted) return;
this.forceUpdate();
}
}, {
key: "render",
value: function render() {
var resetCount = this.state.resetCount;
var children = this.props.children;
var _this$getOnlyChild = this.getOnlyChild(children),
child = _this$getOnlyChild.child,
isFunction = _this$getOnlyChild.isFunction;
// Not need to `cloneElement` since user can handle this in render function self
var returnChildNode;
if (isFunction) {
returnChildNode = child;
} else if ( /*#__PURE__*/React.isValidElement(child)) {
returnChildNode = /*#__PURE__*/React.cloneElement(child, this.getControlled(child.props));
} else {
(0, _warning.default)(!child, '`children` of Field is not validate ReactElement.');
returnChildNode = child;
}
return /*#__PURE__*/React.createElement(React.Fragment, {
key: resetCount
}, returnChildNode);
}
}]);
return Field;
}(React.Component);
(0, _defineProperty2.default)(Field, "contextType", _FieldContext.default);
(0, _defineProperty2.default)(Field, "defaultProps", {
trigger: 'onChange',
valuePropName: 'value'
});
function WrapperField(_ref6) {
var _restProps$isListFiel;
var name = _ref6.name,
restProps = (0, _objectWithoutProperties2.default)(_ref6, _excluded);
var fieldContext = React.useContext(_FieldContext.default);
var listContext = React.useContext(_ListContext.default);
var namePath = name !== undefined ? (0, _valueUtil.getNamePath)(name) : undefined;
var isMergedListField = (_restProps$isListFiel = restProps.isListField) !== null && _restProps$isListFiel !== void 0 ? _restProps$isListFiel : !!listContext;
var key = 'keep';
if (!isMergedListField) {
key = "_".concat((namePath || []).join('_'));
}
// Warning if it's a directly list field.
// We can still support multiple level field preserve.
if (process.env.NODE_ENV !== 'production' && restProps.preserve === false && isMergedListField && namePath.length <= 1) {
(0, _warning.default)(false, '`preserve` should not apply on Form.List fields.');
}
return /*#__PURE__*/React.createElement(Field, (0, _extends2.default)({
key: key,
name: namePath,
isListField: isMergedListField
}, restProps, {
fieldContext: fieldContext
}));
}
var _default = exports.default = WrapperField;

5
node_modules/rc-field-form/lib/FieldContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import * as React from 'react';
import type { InternalFormInstance } from './interface';
export declare const HOOK_MARK = "RC_FORM_INTERNAL_HOOKS";
declare const Context: React.Context<InternalFormInstance>;
export default Context;

51
node_modules/rc-field-form/lib/FieldContext.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.HOOK_MARK = void 0;
var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
var React = _interopRequireWildcard(require("react"));
var HOOK_MARK = exports.HOOK_MARK = 'RC_FORM_INTERNAL_HOOKS';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var warningFunc = function warningFunc() {
(0, _warning.default)(false, 'Can not find FormContext. Please make sure you wrap Field under Form.');
};
var Context = /*#__PURE__*/React.createContext({
getFieldValue: warningFunc,
getFieldsValue: warningFunc,
getFieldError: warningFunc,
getFieldWarning: warningFunc,
getFieldsError: warningFunc,
isFieldsTouched: warningFunc,
isFieldTouched: warningFunc,
isFieldValidating: warningFunc,
isFieldsValidating: warningFunc,
resetFields: warningFunc,
setFields: warningFunc,
setFieldValue: warningFunc,
setFieldsValue: warningFunc,
validateFields: warningFunc,
submit: warningFunc,
getInternalHooks: function getInternalHooks() {
warningFunc();
return {
dispatch: warningFunc,
initEntityValue: warningFunc,
registerField: warningFunc,
useSubscribe: warningFunc,
setInitialValues: warningFunc,
destroyForm: warningFunc,
setCallbacks: warningFunc,
registerWatch: warningFunc,
getFields: warningFunc,
setValidateMessages: warningFunc,
setPreserve: warningFunc,
getInitialValue: warningFunc
};
}
});
var _default = exports.default = Context;

22
node_modules/rc-field-form/lib/Form.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import type { Store, FormInstance, FieldData, ValidateMessages, Callbacks, FormRef } from './interface';
type BaseFormProps = Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onSubmit' | 'children'>;
type RenderProps = (values: Store, form: FormInstance) => JSX.Element | React.ReactNode;
export interface FormProps<Values = any> extends BaseFormProps {
initialValues?: Store;
form?: FormInstance<Values>;
children?: RenderProps | React.ReactNode;
component?: false | string | React.FC<any> | React.ComponentClass<any>;
fields?: FieldData[];
name?: string;
validateMessages?: ValidateMessages;
onValuesChange?: Callbacks<Values>['onValuesChange'];
onFieldsChange?: Callbacks<Values>['onFieldsChange'];
onFinish?: Callbacks<Values>['onFinish'];
onFinishFailed?: Callbacks<Values>['onFinishFailed'];
validateTrigger?: string | string[] | false;
preserve?: boolean;
clearOnDestroy?: boolean;
}
declare const Form: React.ForwardRefRenderFunction<FormRef, FormProps>;
export default Form;

155
node_modules/rc-field-form/lib/Form.js generated vendored Normal file
View File

@@ -0,0 +1,155 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var React = _interopRequireWildcard(require("react"));
var _useForm3 = _interopRequireDefault(require("./useForm"));
var _FieldContext = _interopRequireWildcard(require("./FieldContext"));
var _FormContext = _interopRequireDefault(require("./FormContext"));
var _valueUtil = require("./utils/valueUtil");
var _ListContext = _interopRequireDefault(require("./ListContext"));
var _excluded = ["name", "initialValues", "fields", "form", "preserve", "children", "component", "validateMessages", "validateTrigger", "onValuesChange", "onFieldsChange", "onFinish", "onFinishFailed", "clearOnDestroy"];
var Form = function Form(_ref, ref) {
var name = _ref.name,
initialValues = _ref.initialValues,
fields = _ref.fields,
form = _ref.form,
preserve = _ref.preserve,
children = _ref.children,
_ref$component = _ref.component,
Component = _ref$component === void 0 ? 'form' : _ref$component,
validateMessages = _ref.validateMessages,
_ref$validateTrigger = _ref.validateTrigger,
validateTrigger = _ref$validateTrigger === void 0 ? 'onChange' : _ref$validateTrigger,
onValuesChange = _ref.onValuesChange,
_onFieldsChange = _ref.onFieldsChange,
_onFinish = _ref.onFinish,
onFinishFailed = _ref.onFinishFailed,
clearOnDestroy = _ref.clearOnDestroy,
restProps = (0, _objectWithoutProperties2.default)(_ref, _excluded);
var nativeElementRef = React.useRef(null);
var formContext = React.useContext(_FormContext.default);
// We customize handle event since Context will makes all the consumer re-render:
// https://reactjs.org/docs/context.html#contextprovider
var _useForm = (0, _useForm3.default)(form),
_useForm2 = (0, _slicedToArray2.default)(_useForm, 1),
formInstance = _useForm2[0];
var _getInternalHooks = formInstance.getInternalHooks(_FieldContext.HOOK_MARK),
useSubscribe = _getInternalHooks.useSubscribe,
setInitialValues = _getInternalHooks.setInitialValues,
setCallbacks = _getInternalHooks.setCallbacks,
setValidateMessages = _getInternalHooks.setValidateMessages,
setPreserve = _getInternalHooks.setPreserve,
destroyForm = _getInternalHooks.destroyForm;
// Pass ref with form instance
React.useImperativeHandle(ref, function () {
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, formInstance), {}, {
nativeElement: nativeElementRef.current
});
});
// Register form into Context
React.useEffect(function () {
formContext.registerForm(name, formInstance);
return function () {
formContext.unregisterForm(name);
};
}, [formContext, formInstance, name]);
// Pass props to store
setValidateMessages((0, _objectSpread2.default)((0, _objectSpread2.default)({}, formContext.validateMessages), validateMessages));
setCallbacks({
onValuesChange: onValuesChange,
onFieldsChange: function onFieldsChange(changedFields) {
formContext.triggerFormChange(name, changedFields);
if (_onFieldsChange) {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
_onFieldsChange.apply(void 0, [changedFields].concat(rest));
}
},
onFinish: function onFinish(values) {
formContext.triggerFormFinish(name, values);
if (_onFinish) {
_onFinish(values);
}
},
onFinishFailed: onFinishFailed
});
setPreserve(preserve);
// Set initial value, init store value when first mount
var mountRef = React.useRef(null);
setInitialValues(initialValues, !mountRef.current);
if (!mountRef.current) {
mountRef.current = true;
}
React.useEffect(function () {
return function () {
return destroyForm(clearOnDestroy);
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]);
// Prepare children by `children` type
var childrenNode;
var childrenRenderProps = typeof children === 'function';
if (childrenRenderProps) {
var _values = formInstance.getFieldsValue(true);
childrenNode = children(_values, formInstance);
} else {
childrenNode = children;
}
// Not use subscribe when using render props
useSubscribe(!childrenRenderProps);
// Listen if fields provided. We use ref to save prev data here to avoid additional render
var prevFieldsRef = React.useRef();
React.useEffect(function () {
if (!(0, _valueUtil.isSimilar)(prevFieldsRef.current || [], fields || [])) {
formInstance.setFields(fields || []);
}
prevFieldsRef.current = fields;
}, [fields, formInstance]);
var formContextValue = React.useMemo(function () {
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, formInstance), {}, {
validateTrigger: validateTrigger
});
}, [formInstance, validateTrigger]);
var wrapperNode = /*#__PURE__*/React.createElement(_ListContext.default.Provider, {
value: null
}, /*#__PURE__*/React.createElement(_FieldContext.default.Provider, {
value: formContextValue
}, childrenNode));
if (Component === false) {
return wrapperNode;
}
return /*#__PURE__*/React.createElement(Component, (0, _extends2.default)({}, restProps, {
ref: nativeElementRef,
onSubmit: function onSubmit(event) {
event.preventDefault();
event.stopPropagation();
formInstance.submit();
},
onReset: function onReset(event) {
var _restProps$onReset;
event.preventDefault();
formInstance.resetFields();
(_restProps$onReset = restProps.onReset) === null || _restProps$onReset === void 0 || _restProps$onReset.call(restProps, event);
}
}), wrapperNode);
};
var _default = exports.default = Form;

27
node_modules/rc-field-form/lib/FormContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import * as React from 'react';
import type { ValidateMessages, FormInstance, FieldData, Store } from './interface';
export type Forms = Record<string, FormInstance>;
export interface FormChangeInfo {
changedFields: FieldData[];
forms: Forms;
}
export interface FormFinishInfo {
values: Store;
forms: Forms;
}
export interface FormProviderProps {
validateMessages?: ValidateMessages;
onFormChange?: (name: string, info: FormChangeInfo) => void;
onFormFinish?: (name: string, info: FormFinishInfo) => void;
children?: React.ReactNode;
}
export interface FormContextProps extends FormProviderProps {
triggerFormChange: (name: string, changedFields: FieldData[]) => void;
triggerFormFinish: (name: string, values: Store) => void;
registerForm: (name: string, form: FormInstance) => void;
unregisterForm: (name: string) => void;
}
declare const FormContext: React.Context<FormContextProps>;
declare const FormProvider: React.FunctionComponent<FormProviderProps>;
export { FormProvider };
export default FormContext;

64
node_modules/rc-field-form/lib/FormContext.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.FormProvider = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _objectSpread3 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var React = _interopRequireWildcard(require("react"));
var FormContext = /*#__PURE__*/React.createContext({
triggerFormChange: function triggerFormChange() {},
triggerFormFinish: function triggerFormFinish() {},
registerForm: function registerForm() {},
unregisterForm: function unregisterForm() {}
});
var FormProvider = exports.FormProvider = function FormProvider(_ref) {
var validateMessages = _ref.validateMessages,
onFormChange = _ref.onFormChange,
onFormFinish = _ref.onFormFinish,
children = _ref.children;
var formContext = React.useContext(FormContext);
var formsRef = React.useRef({});
return /*#__PURE__*/React.createElement(FormContext.Provider, {
value: (0, _objectSpread3.default)((0, _objectSpread3.default)({}, formContext), {}, {
validateMessages: (0, _objectSpread3.default)((0, _objectSpread3.default)({}, formContext.validateMessages), validateMessages),
// =========================================================
// = Global Form Control =
// =========================================================
triggerFormChange: function triggerFormChange(name, changedFields) {
if (onFormChange) {
onFormChange(name, {
changedFields: changedFields,
forms: formsRef.current
});
}
formContext.triggerFormChange(name, changedFields);
},
triggerFormFinish: function triggerFormFinish(name, values) {
if (onFormFinish) {
onFormFinish(name, {
values: values,
forms: formsRef.current
});
}
formContext.triggerFormFinish(name, values);
},
registerForm: function registerForm(name, form) {
if (name) {
formsRef.current = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, formsRef.current), {}, (0, _defineProperty2.default)({}, name, form));
}
formContext.registerForm(name, form);
},
unregisterForm: function unregisterForm(name) {
var newForms = (0, _objectSpread3.default)({}, formsRef.current);
delete newForms[name];
formsRef.current = newForms;
formContext.unregisterForm(name);
}
})
}, children);
};
var _default = exports.default = FormContext;

23
node_modules/rc-field-form/lib/List.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import * as React from 'react';
import type { NamePath, StoreValue, ValidatorRule, Meta } from './interface';
export interface ListField {
name: number;
key: number;
isListField: boolean;
}
export interface ListOperations {
add: (defaultValue?: StoreValue, index?: number) => void;
remove: (index: number | number[]) => void;
move: (from: number, to: number) => void;
}
export interface ListProps<Values = any> {
name: NamePath<Values>;
rules?: ValidatorRule[];
validateTrigger?: string | string[] | false;
initialValue?: any[];
children?: (fields: ListField[], operations: ListOperations, meta: Meta) => JSX.Element | React.ReactNode;
/** @private Passed by Form.List props. Do not use since it will break by path check. */
isListField?: boolean;
}
declare function List<Values = any>({ name, initialValue, children, rules, validateTrigger, isListField, }: ListProps<Values>): React.JSX.Element;
export default List;

157
node_modules/rc-field-form/lib/List.js generated vendored Normal file
View File

@@ -0,0 +1,157 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var React = _interopRequireWildcard(require("react"));
var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
var _FieldContext = _interopRequireDefault(require("./FieldContext"));
var _Field = _interopRequireDefault(require("./Field"));
var _valueUtil = require("./utils/valueUtil");
var _ListContext = _interopRequireDefault(require("./ListContext"));
function List(_ref) {
var name = _ref.name,
initialValue = _ref.initialValue,
children = _ref.children,
rules = _ref.rules,
validateTrigger = _ref.validateTrigger,
isListField = _ref.isListField;
var context = React.useContext(_FieldContext.default);
var wrapperListContext = React.useContext(_ListContext.default);
var keyRef = React.useRef({
keys: [],
id: 0
});
var keyManager = keyRef.current;
var prefixName = React.useMemo(function () {
var parentPrefixName = (0, _valueUtil.getNamePath)(context.prefixName) || [];
return [].concat((0, _toConsumableArray2.default)(parentPrefixName), (0, _toConsumableArray2.default)((0, _valueUtil.getNamePath)(name)));
}, [context.prefixName, name]);
var fieldContext = React.useMemo(function () {
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, context), {}, {
prefixName: prefixName
});
}, [context, prefixName]);
// List context
var listContext = React.useMemo(function () {
return {
getKey: function getKey(namePath) {
var len = prefixName.length;
var pathName = namePath[len];
return [keyManager.keys[pathName], namePath.slice(len + 1)];
}
};
}, [prefixName]);
// User should not pass `children` as other type.
if (typeof children !== 'function') {
(0, _warning.default)(false, 'Form.List only accepts function as children.');
return null;
}
var shouldUpdate = function shouldUpdate(prevValue, nextValue, _ref2) {
var source = _ref2.source;
if (source === 'internal') {
return false;
}
return prevValue !== nextValue;
};
return /*#__PURE__*/React.createElement(_ListContext.default.Provider, {
value: listContext
}, /*#__PURE__*/React.createElement(_FieldContext.default.Provider, {
value: fieldContext
}, /*#__PURE__*/React.createElement(_Field.default, {
name: [],
shouldUpdate: shouldUpdate,
rules: rules,
validateTrigger: validateTrigger,
initialValue: initialValue,
isList: true,
isListField: isListField !== null && isListField !== void 0 ? isListField : !!wrapperListContext
}, function (_ref3, meta) {
var _ref3$value = _ref3.value,
value = _ref3$value === void 0 ? [] : _ref3$value,
onChange = _ref3.onChange;
var getFieldValue = context.getFieldValue;
var getNewValue = function getNewValue() {
var values = getFieldValue(prefixName || []);
return values || [];
};
/**
* Always get latest value in case user update fields by `form` api.
*/
var operations = {
add: function add(defaultValue, index) {
// Mapping keys
var newValue = getNewValue();
if (index >= 0 && index <= newValue.length) {
keyManager.keys = [].concat((0, _toConsumableArray2.default)(keyManager.keys.slice(0, index)), [keyManager.id], (0, _toConsumableArray2.default)(keyManager.keys.slice(index)));
onChange([].concat((0, _toConsumableArray2.default)(newValue.slice(0, index)), [defaultValue], (0, _toConsumableArray2.default)(newValue.slice(index))));
} else {
if (process.env.NODE_ENV !== 'production' && (index < 0 || index > newValue.length)) {
(0, _warning.default)(false, 'The second parameter of the add function should be a valid positive number.');
}
keyManager.keys = [].concat((0, _toConsumableArray2.default)(keyManager.keys), [keyManager.id]);
onChange([].concat((0, _toConsumableArray2.default)(newValue), [defaultValue]));
}
keyManager.id += 1;
},
remove: function remove(index) {
var newValue = getNewValue();
var indexSet = new Set(Array.isArray(index) ? index : [index]);
if (indexSet.size <= 0) {
return;
}
keyManager.keys = keyManager.keys.filter(function (_, keysIndex) {
return !indexSet.has(keysIndex);
});
// Trigger store change
onChange(newValue.filter(function (_, valueIndex) {
return !indexSet.has(valueIndex);
}));
},
move: function move(from, to) {
if (from === to) {
return;
}
var newValue = getNewValue();
// Do not handle out of range
if (from < 0 || from >= newValue.length || to < 0 || to >= newValue.length) {
return;
}
keyManager.keys = (0, _valueUtil.move)(keyManager.keys, from, to);
// Trigger store change
onChange((0, _valueUtil.move)(newValue, from, to));
}
};
var listValue = value || [];
if (!Array.isArray(listValue)) {
listValue = [];
if (process.env.NODE_ENV !== 'production') {
(0, _warning.default)(false, "Current value of '".concat(prefixName.join(' > '), "' is not an array type."));
}
}
return children(listValue.map(function (__, index) {
var key = keyManager.keys[index];
if (key === undefined) {
keyManager.keys[index] = keyManager.id;
key = keyManager.keys[index];
keyManager.id += 1;
}
return {
name: index,
key: key,
isListField: true
};
}), operations, meta);
})));
}
var _default = exports.default = List;

7
node_modules/rc-field-form/lib/ListContext.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import * as React from 'react';
import type { InternalNamePath } from './interface';
export interface ListContextProps {
getKey: (namePath: InternalNamePath) => [InternalNamePath[number], InternalNamePath];
}
declare const ListContext: React.Context<ListContextProps>;
export default ListContext;

10
node_modules/rc-field-form/lib/ListContext.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var ListContext = /*#__PURE__*/React.createContext(null);
var _default = exports.default = ListContext;

25
node_modules/rc-field-form/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import * as React from 'react';
import type { FormRef, FormInstance } from './interface';
import Field from './Field';
import List from './List';
import useForm from './useForm';
import type { FormProps } from './Form';
import { FormProvider } from './FormContext';
import FieldContext from './FieldContext';
import ListContext from './ListContext';
import useWatch from './useWatch';
declare const InternalForm: <Values = any>(props: FormProps<Values> & {
ref?: React.Ref<FormRef<Values>>;
}) => React.ReactElement;
type InternalFormType = typeof InternalForm;
interface RefFormType extends InternalFormType {
FormProvider: typeof FormProvider;
Field: typeof Field;
List: typeof List;
useForm: typeof useForm;
useWatch: typeof useWatch;
}
declare const RefForm: RefFormType;
export { Field, List, useForm, FormProvider, FieldContext, ListContext, useWatch };
export type { FormProps, FormInstance, FormRef };
export default RefForm;

67
node_modules/rc-field-form/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,67 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "Field", {
enumerable: true,
get: function get() {
return _Field.default;
}
});
Object.defineProperty(exports, "FieldContext", {
enumerable: true,
get: function get() {
return _FieldContext.default;
}
});
Object.defineProperty(exports, "FormProvider", {
enumerable: true,
get: function get() {
return _FormContext.FormProvider;
}
});
Object.defineProperty(exports, "List", {
enumerable: true,
get: function get() {
return _List.default;
}
});
Object.defineProperty(exports, "ListContext", {
enumerable: true,
get: function get() {
return _ListContext.default;
}
});
exports.default = void 0;
Object.defineProperty(exports, "useForm", {
enumerable: true,
get: function get() {
return _useForm.default;
}
});
Object.defineProperty(exports, "useWatch", {
enumerable: true,
get: function get() {
return _useWatch.default;
}
});
var React = _interopRequireWildcard(require("react"));
var _Field = _interopRequireDefault(require("./Field"));
var _List = _interopRequireDefault(require("./List"));
var _useForm = _interopRequireDefault(require("./useForm"));
var _Form = _interopRequireDefault(require("./Form"));
var _FormContext = require("./FormContext");
var _FieldContext = _interopRequireDefault(require("./FieldContext"));
var _ListContext = _interopRequireDefault(require("./ListContext"));
var _useWatch = _interopRequireDefault(require("./useWatch"));
var InternalForm = /*#__PURE__*/React.forwardRef(_Form.default);
var RefForm = InternalForm;
RefForm.FormProvider = _FormContext.FormProvider;
RefForm.Field = _Field.default;
RefForm.List = _List.default;
RefForm.useForm = _useForm.default;
RefForm.useWatch = _useWatch.default;
var _default = exports.default = RefForm;

265
node_modules/rc-field-form/lib/interface.d.ts generated vendored Normal file
View File

@@ -0,0 +1,265 @@
import type { ReactElement } from 'react';
import type { DeepNamePath } from './namePathType';
import type { ReducerAction } from './useForm';
export type InternalNamePath = (string | number)[];
export type NamePath<T = any> = DeepNamePath<T>;
export type StoreValue = any;
export type Store = Record<string, StoreValue>;
export interface Meta {
touched: boolean;
validating: boolean;
errors: string[];
warnings: string[];
name: InternalNamePath;
validated: boolean;
}
export interface InternalFieldData extends Meta {
value: StoreValue;
}
/**
* Used by `setFields` config
*/
export interface FieldData<Values = any> extends Partial<Omit<InternalFieldData, 'name'>> {
name: NamePath<Values>;
}
export type RuleType = 'string' | 'number' | 'boolean' | 'method' | 'regexp' | 'integer' | 'float' | 'object' | 'enum' | 'date' | 'url' | 'hex' | 'email';
type Validator = (rule: RuleObject, value: StoreValue, callback: (error?: string) => void) => Promise<void | any> | void;
export type RuleRender = (form: FormInstance) => RuleObject;
export interface ValidatorRule {
warningOnly?: boolean;
message?: string | ReactElement;
validator: Validator;
}
interface BaseRule {
warningOnly?: boolean;
enum?: StoreValue[];
len?: number;
max?: number;
message?: string | ReactElement;
min?: number;
pattern?: RegExp;
required?: boolean;
transform?: (value: StoreValue) => StoreValue;
type?: RuleType;
whitespace?: boolean;
/** Customize rule level `validateTrigger`. Must be subset of Field `validateTrigger` */
validateTrigger?: string | string[];
}
type AggregationRule = BaseRule & Partial<ValidatorRule>;
interface ArrayRule extends Omit<AggregationRule, 'type'> {
type: 'array';
defaultField?: RuleObject;
}
export type RuleObject = AggregationRule | ArrayRule;
export type Rule = RuleObject | RuleRender;
export interface ValidateErrorEntity<Values = any> {
values: Values;
errorFields: {
name: InternalNamePath;
errors: string[];
}[];
outOfDate: boolean;
}
export interface FieldEntity {
onStoreChange: (store: Store, namePathList: InternalNamePath[] | null, info: ValuedNotifyInfo) => void;
isFieldTouched: () => boolean;
isFieldDirty: () => boolean;
isFieldValidating: () => boolean;
isListField: () => boolean;
isList: () => boolean;
isPreserve: () => boolean;
validateRules: (options?: InternalValidateOptions) => Promise<RuleError[]>;
getMeta: () => Meta;
getNamePath: () => InternalNamePath;
getErrors: () => string[];
getWarnings: () => string[];
props: {
name?: NamePath;
rules?: Rule[];
dependencies?: NamePath[];
initialValue?: any;
};
}
export interface FieldError {
name: InternalNamePath;
errors: string[];
warnings: string[];
}
export interface RuleError {
errors: string[];
rule: RuleObject;
}
export interface ValidateOptions {
/**
* Validate only and not trigger UI and Field status update
*/
validateOnly?: boolean;
/**
* Recursive validate. It will validate all the name path that contains the provided one.
* e.g. [['a']] will validate ['a'] , ['a', 'b'] and ['a', 1].
*/
recursive?: boolean;
/** Validate when a field is dirty (validated or touched) */
dirty?: boolean;
}
export type ValidateFields<Values = any> = {
(opt?: ValidateOptions): Promise<Values>;
(nameList?: NamePath[], opt?: ValidateOptions): Promise<Values>;
};
export interface InternalValidateOptions extends ValidateOptions {
triggerName?: string;
validateMessages?: ValidateMessages;
}
export type InternalValidateFields<Values = any> = {
(options?: InternalValidateOptions): Promise<Values>;
(nameList?: NamePath[], options?: InternalValidateOptions): Promise<Values>;
};
interface ValueUpdateInfo {
type: 'valueUpdate';
source: 'internal' | 'external';
}
interface ValidateFinishInfo {
type: 'validateFinish';
}
interface ResetInfo {
type: 'reset';
}
interface RemoveInfo {
type: 'remove';
}
interface SetFieldInfo {
type: 'setField';
data: FieldData;
}
interface DependenciesUpdateInfo {
type: 'dependenciesUpdate';
/**
* Contains all the related `InternalNamePath[]`.
* a <- b <- c : change `a`
* relatedFields=[a, b, c]
*/
relatedFields: InternalNamePath[];
}
export type NotifyInfo = ValueUpdateInfo | ValidateFinishInfo | ResetInfo | RemoveInfo | SetFieldInfo | DependenciesUpdateInfo;
export type ValuedNotifyInfo = NotifyInfo & {
store: Store;
};
export interface Callbacks<Values = any> {
onValuesChange?: (changedValues: any, values: Values) => void;
onFieldsChange?: (changedFields: FieldData[], allFields: FieldData[]) => void;
onFinish?: (values: Values) => void;
onFinishFailed?: (errorInfo: ValidateErrorEntity<Values>) => void;
}
export type WatchCallBack = (values: Store, allValues: Store, namePathList: InternalNamePath[]) => void;
export interface WatchOptions<Form extends FormInstance = FormInstance> {
form?: Form;
preserve?: boolean;
}
export interface InternalHooks {
dispatch: (action: ReducerAction) => void;
initEntityValue: (entity: FieldEntity) => void;
registerField: (entity: FieldEntity) => () => void;
useSubscribe: (subscribable: boolean) => void;
setInitialValues: (values: Store, init: boolean) => void;
destroyForm: (clearOnDestroy?: boolean) => void;
setCallbacks: (callbacks: Callbacks) => void;
registerWatch: (callback: WatchCallBack) => () => void;
getFields: (namePathList?: InternalNamePath[]) => FieldData[];
setValidateMessages: (validateMessages: ValidateMessages) => void;
setPreserve: (preserve?: boolean) => void;
getInitialValue: (namePath: InternalNamePath) => StoreValue;
}
/** Only return partial when type is not any */
type RecursivePartial<T> = NonNullable<T> extends object ? {
[P in keyof T]?: NonNullable<T[P]> extends (infer U)[] ? RecursivePartial<U>[] : NonNullable<T[P]> extends object ? RecursivePartial<T[P]> : T[P];
} : T;
export type FilterFunc = (meta: Meta) => boolean;
export type GetFieldsValueConfig = {
strict?: boolean;
filter?: FilterFunc;
};
export interface FormInstance<Values = any> {
getFieldValue: (name: NamePath<Values>) => StoreValue;
getFieldsValue: (() => Values) & ((nameList: NamePath<Values>[] | true, filterFunc?: FilterFunc) => any) & ((config: GetFieldsValueConfig) => any);
getFieldError: (name: NamePath<Values>) => string[];
getFieldsError: (nameList?: NamePath<Values>[]) => FieldError[];
getFieldWarning: (name: NamePath<Values>) => string[];
isFieldsTouched: ((nameList?: NamePath<Values>[], allFieldsTouched?: boolean) => boolean) & ((allFieldsTouched?: boolean) => boolean);
isFieldTouched: (name: NamePath<Values>) => boolean;
isFieldValidating: (name: NamePath<Values>) => boolean;
isFieldsValidating: (nameList?: NamePath<Values>[]) => boolean;
resetFields: (fields?: NamePath<Values>[]) => void;
setFields: (fields: FieldData<Values>[]) => void;
setFieldValue: (name: NamePath<Values>, value: any) => void;
setFieldsValue: (values: RecursivePartial<Values>) => void;
validateFields: ValidateFields<Values>;
submit: () => void;
}
export type FormRef<Values = any> = FormInstance<Values> & {
nativeElement?: HTMLElement;
};
export type InternalFormInstance = Omit<FormInstance, 'validateFields'> & {
validateFields: InternalValidateFields;
/**
* Passed by field context props
*/
prefixName?: InternalNamePath;
validateTrigger?: string | string[] | false;
/**
* Form component should register some content into store.
* We pass the `HOOK_MARK` as key to avoid user call the function.
*/
getInternalHooks: (secret: string) => InternalHooks | null;
/** @private Internal usage. Do not use it in your production */
_init?: boolean;
};
export type EventArgs = any[];
type ValidateMessage = string | (() => string);
export interface ValidateMessages {
default?: ValidateMessage;
required?: ValidateMessage;
enum?: ValidateMessage;
whitespace?: ValidateMessage;
date?: {
format?: ValidateMessage;
parse?: ValidateMessage;
invalid?: ValidateMessage;
};
types?: {
string?: ValidateMessage;
method?: ValidateMessage;
array?: ValidateMessage;
object?: ValidateMessage;
number?: ValidateMessage;
date?: ValidateMessage;
boolean?: ValidateMessage;
integer?: ValidateMessage;
float?: ValidateMessage;
regexp?: ValidateMessage;
email?: ValidateMessage;
url?: ValidateMessage;
hex?: ValidateMessage;
};
string?: {
len?: ValidateMessage;
min?: ValidateMessage;
max?: ValidateMessage;
range?: ValidateMessage;
};
number?: {
len?: ValidateMessage;
min?: ValidateMessage;
max?: ValidateMessage;
range?: ValidateMessage;
};
array?: {
len?: ValidateMessage;
min?: ValidateMessage;
max?: ValidateMessage;
range?: ValidateMessage;
};
pattern?: {
mismatch?: ValidateMessage;
};
}
export {};

5
node_modules/rc-field-form/lib/interface.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});

13
node_modules/rc-field-form/lib/namePathType.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
type BaseNamePath = string | number | boolean | (string | number | boolean)[];
/**
* Store: The store type from `FormInstance<Store>`
* ParentNamePath: Auto generate by nest logic. Do not fill manually.
*/
export type DeepNamePath<Store = any, ParentNamePath extends any[] = []> = ParentNamePath['length'] extends 5 ? never : true extends (Store extends BaseNamePath ? true : false) ? ParentNamePath['length'] extends 0 ? Store | BaseNamePath : Store extends any[] ? [...ParentNamePath, number] : never : Store extends any[] ? // Connect path. e.g. { a: { b: string }[] }
[
...ParentNamePath,
number
] | DeepNamePath<Store[number], [...ParentNamePath, number]> : keyof Store extends never ? Store : {
[FieldKey in keyof Store]: Store[FieldKey] extends Function ? never : (ParentNamePath['length'] extends 0 ? FieldKey : never) | [...ParentNamePath, FieldKey] | DeepNamePath<Required<Store>[FieldKey], [...ParentNamePath, FieldKey]>;
}[keyof Store];
export {};

5
node_modules/rc-field-form/lib/namePathType.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});

94
node_modules/rc-field-form/lib/useForm.d.ts generated vendored Normal file
View File

@@ -0,0 +1,94 @@
import type { FormInstance, InternalFormInstance, InternalNamePath, StoreValue } from './interface';
interface UpdateAction {
type: 'updateValue';
namePath: InternalNamePath;
value: StoreValue;
}
interface ValidateAction {
type: 'validateField';
namePath: InternalNamePath;
triggerName: string;
}
export type ReducerAction = UpdateAction | ValidateAction;
export declare class FormStore {
private formHooked;
private forceRootUpdate;
private subscribable;
private store;
private fieldEntities;
private initialValues;
private callbacks;
private validateMessages;
private preserve?;
private lastValidatePromise;
constructor(forceRootUpdate: () => void);
getForm: () => InternalFormInstance;
private getInternalHooks;
private useSubscribe;
/**
* Record prev Form unmount fieldEntities which config preserve false.
* This need to be refill with initialValues instead of store value.
*/
private prevWithoutPreserves;
/**
* First time `setInitialValues` should update store with initial value
*/
private setInitialValues;
private destroyForm;
private getInitialValue;
private setCallbacks;
private setValidateMessages;
private setPreserve;
private watchList;
private registerWatch;
private notifyWatch;
private timeoutId;
private warningUnhooked;
private updateStore;
/**
* Get registered field entities.
* @param pure Only return field which has a `name`. Default: false
*/
private getFieldEntities;
private getFieldsMap;
private getFieldEntitiesForNamePathList;
private getFieldsValue;
private getFieldValue;
private getFieldsError;
private getFieldError;
private getFieldWarning;
private isFieldsTouched;
private isFieldTouched;
private isFieldsValidating;
private isFieldValidating;
/**
* Reset Field with field `initialValue` prop.
* Can pass `entities` or `namePathList` or just nothing.
*/
private resetWithFieldInitialValue;
private resetFields;
private setFields;
private getFields;
/**
* This only trigger when a field is on constructor to avoid we get initialValue too late
*/
private initEntityValue;
private isMergedPreserve;
private registerField;
private dispatch;
private notifyObservers;
/**
* Notify dependencies children with parent update
* We need delay to trigger validate in case Field is under render props
*/
private triggerDependenciesUpdate;
private updateValue;
private setFieldsValue;
private setFieldValue;
private getDependencyChildrenFields;
private triggerOnFieldsChange;
private validateFields;
private submit;
}
declare function useForm<Values = any>(form?: FormInstance<Values>): [FormInstance<Values>];
export default useForm;

905
node_modules/rc-field-form/lib/useForm.js generated vendored Normal file
View File

@@ -0,0 +1,905 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.FormStore = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _set = require("rc-util/lib/utils/set");
var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
var React = _interopRequireWildcard(require("react"));
var _FieldContext = require("./FieldContext");
var _asyncUtil = require("./utils/asyncUtil");
var _messages = require("./utils/messages");
var _NameMap = _interopRequireDefault(require("./utils/NameMap"));
var _valueUtil = require("./utils/valueUtil");
var _excluded = ["name"];
var FormStore = exports.FormStore = /*#__PURE__*/(0, _createClass2.default)(function FormStore(forceRootUpdate) {
var _this = this;
(0, _classCallCheck2.default)(this, FormStore);
(0, _defineProperty2.default)(this, "formHooked", false);
(0, _defineProperty2.default)(this, "forceRootUpdate", void 0);
(0, _defineProperty2.default)(this, "subscribable", true);
(0, _defineProperty2.default)(this, "store", {});
(0, _defineProperty2.default)(this, "fieldEntities", []);
(0, _defineProperty2.default)(this, "initialValues", {});
(0, _defineProperty2.default)(this, "callbacks", {});
(0, _defineProperty2.default)(this, "validateMessages", null);
(0, _defineProperty2.default)(this, "preserve", null);
(0, _defineProperty2.default)(this, "lastValidatePromise", null);
(0, _defineProperty2.default)(this, "getForm", function () {
return {
getFieldValue: _this.getFieldValue,
getFieldsValue: _this.getFieldsValue,
getFieldError: _this.getFieldError,
getFieldWarning: _this.getFieldWarning,
getFieldsError: _this.getFieldsError,
isFieldsTouched: _this.isFieldsTouched,
isFieldTouched: _this.isFieldTouched,
isFieldValidating: _this.isFieldValidating,
isFieldsValidating: _this.isFieldsValidating,
resetFields: _this.resetFields,
setFields: _this.setFields,
setFieldValue: _this.setFieldValue,
setFieldsValue: _this.setFieldsValue,
validateFields: _this.validateFields,
submit: _this.submit,
_init: true,
getInternalHooks: _this.getInternalHooks
};
});
// ======================== Internal Hooks ========================
(0, _defineProperty2.default)(this, "getInternalHooks", function (key) {
if (key === _FieldContext.HOOK_MARK) {
_this.formHooked = true;
return {
dispatch: _this.dispatch,
initEntityValue: _this.initEntityValue,
registerField: _this.registerField,
useSubscribe: _this.useSubscribe,
setInitialValues: _this.setInitialValues,
destroyForm: _this.destroyForm,
setCallbacks: _this.setCallbacks,
setValidateMessages: _this.setValidateMessages,
getFields: _this.getFields,
setPreserve: _this.setPreserve,
getInitialValue: _this.getInitialValue,
registerWatch: _this.registerWatch
};
}
(0, _warning.default)(false, '`getInternalHooks` is internal usage. Should not call directly.');
return null;
});
(0, _defineProperty2.default)(this, "useSubscribe", function (subscribable) {
_this.subscribable = subscribable;
});
/**
* Record prev Form unmount fieldEntities which config preserve false.
* This need to be refill with initialValues instead of store value.
*/
(0, _defineProperty2.default)(this, "prevWithoutPreserves", null);
/**
* First time `setInitialValues` should update store with initial value
*/
(0, _defineProperty2.default)(this, "setInitialValues", function (initialValues, init) {
_this.initialValues = initialValues || {};
if (init) {
var _this$prevWithoutPres;
var nextStore = (0, _set.merge)(initialValues, _this.store);
// We will take consider prev form unmount fields.
// When the field is not `preserve`, we need fill this with initialValues instead of store.
// eslint-disable-next-line array-callback-return
(_this$prevWithoutPres = _this.prevWithoutPreserves) === null || _this$prevWithoutPres === void 0 || _this$prevWithoutPres.map(function (_ref) {
var namePath = _ref.key;
nextStore = (0, _valueUtil.setValue)(nextStore, namePath, (0, _valueUtil.getValue)(initialValues, namePath));
});
_this.prevWithoutPreserves = null;
_this.updateStore(nextStore);
}
});
(0, _defineProperty2.default)(this, "destroyForm", function (clearOnDestroy) {
if (clearOnDestroy) {
// destroy form reset store
_this.updateStore({});
} else {
// Fill preserve fields
var prevWithoutPreserves = new _NameMap.default();
_this.getFieldEntities(true).forEach(function (entity) {
if (!_this.isMergedPreserve(entity.isPreserve())) {
prevWithoutPreserves.set(entity.getNamePath(), true);
}
});
_this.prevWithoutPreserves = prevWithoutPreserves;
}
});
(0, _defineProperty2.default)(this, "getInitialValue", function (namePath) {
var initValue = (0, _valueUtil.getValue)(_this.initialValues, namePath);
// Not cloneDeep when without `namePath`
return namePath.length ? (0, _set.merge)(initValue) : initValue;
});
(0, _defineProperty2.default)(this, "setCallbacks", function (callbacks) {
_this.callbacks = callbacks;
});
(0, _defineProperty2.default)(this, "setValidateMessages", function (validateMessages) {
_this.validateMessages = validateMessages;
});
(0, _defineProperty2.default)(this, "setPreserve", function (preserve) {
_this.preserve = preserve;
});
// ============================= Watch ============================
(0, _defineProperty2.default)(this, "watchList", []);
(0, _defineProperty2.default)(this, "registerWatch", function (callback) {
_this.watchList.push(callback);
return function () {
_this.watchList = _this.watchList.filter(function (fn) {
return fn !== callback;
});
};
});
(0, _defineProperty2.default)(this, "notifyWatch", function () {
var namePath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
// No need to cost perf when nothing need to watch
if (_this.watchList.length) {
var values = _this.getFieldsValue();
var allValues = _this.getFieldsValue(true);
_this.watchList.forEach(function (callback) {
callback(values, allValues, namePath);
});
}
});
// ========================== Dev Warning =========================
(0, _defineProperty2.default)(this, "timeoutId", null);
(0, _defineProperty2.default)(this, "warningUnhooked", function () {
if (process.env.NODE_ENV !== 'production' && !_this.timeoutId && typeof window !== 'undefined') {
_this.timeoutId = setTimeout(function () {
_this.timeoutId = null;
if (!_this.formHooked) {
(0, _warning.default)(false, 'Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?');
}
});
}
});
// ============================ Store =============================
(0, _defineProperty2.default)(this, "updateStore", function (nextStore) {
_this.store = nextStore;
});
// ============================ Fields ============================
/**
* Get registered field entities.
* @param pure Only return field which has a `name`. Default: false
*/
(0, _defineProperty2.default)(this, "getFieldEntities", function () {
var pure = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!pure) {
return _this.fieldEntities;
}
return _this.fieldEntities.filter(function (field) {
return field.getNamePath().length;
});
});
(0, _defineProperty2.default)(this, "getFieldsMap", function () {
var pure = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var cache = new _NameMap.default();
_this.getFieldEntities(pure).forEach(function (field) {
var namePath = field.getNamePath();
cache.set(namePath, field);
});
return cache;
});
(0, _defineProperty2.default)(this, "getFieldEntitiesForNamePathList", function (nameList) {
if (!nameList) {
return _this.getFieldEntities(true);
}
var cache = _this.getFieldsMap(true);
return nameList.map(function (name) {
var namePath = (0, _valueUtil.getNamePath)(name);
return cache.get(namePath) || {
INVALIDATE_NAME_PATH: (0, _valueUtil.getNamePath)(name)
};
});
});
(0, _defineProperty2.default)(this, "getFieldsValue", function (nameList, filterFunc) {
_this.warningUnhooked();
// Fill args
var mergedNameList;
var mergedFilterFunc;
var mergedStrict;
if (nameList === true || Array.isArray(nameList)) {
mergedNameList = nameList;
mergedFilterFunc = filterFunc;
} else if (nameList && (0, _typeof2.default)(nameList) === 'object') {
mergedStrict = nameList.strict;
mergedFilterFunc = nameList.filter;
}
if (mergedNameList === true && !mergedFilterFunc) {
return _this.store;
}
var fieldEntities = _this.getFieldEntitiesForNamePathList(Array.isArray(mergedNameList) ? mergedNameList : null);
var filteredNameList = [];
fieldEntities.forEach(function (entity) {
var _isListField, _ref3;
var 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 (mergedStrict) {
var _isList, _ref2;
if ((_isList = (_ref2 = entity).isList) !== null && _isList !== void 0 && _isList.call(_ref2)) {
return;
}
} else if (!mergedNameList && (_isListField = (_ref3 = entity).isListField) !== null && _isListField !== void 0 && _isListField.call(_ref3)) {
return;
}
if (!mergedFilterFunc) {
filteredNameList.push(namePath);
} else {
var meta = 'getMeta' in entity ? entity.getMeta() : null;
if (mergedFilterFunc(meta)) {
filteredNameList.push(namePath);
}
}
});
return (0, _valueUtil.cloneByNamePathList)(_this.store, filteredNameList.map(_valueUtil.getNamePath));
});
(0, _defineProperty2.default)(this, "getFieldValue", function (name) {
_this.warningUnhooked();
var namePath = (0, _valueUtil.getNamePath)(name);
return (0, _valueUtil.getValue)(_this.store, namePath);
});
(0, _defineProperty2.default)(this, "getFieldsError", function (nameList) {
_this.warningUnhooked();
var fieldEntities = _this.getFieldEntitiesForNamePathList(nameList);
return fieldEntities.map(function (entity, index) {
if (entity && !('INVALIDATE_NAME_PATH' in entity)) {
return {
name: entity.getNamePath(),
errors: entity.getErrors(),
warnings: entity.getWarnings()
};
}
return {
name: (0, _valueUtil.getNamePath)(nameList[index]),
errors: [],
warnings: []
};
});
});
(0, _defineProperty2.default)(this, "getFieldError", function (name) {
_this.warningUnhooked();
var namePath = (0, _valueUtil.getNamePath)(name);
var fieldError = _this.getFieldsError([namePath])[0];
return fieldError.errors;
});
(0, _defineProperty2.default)(this, "getFieldWarning", function (name) {
_this.warningUnhooked();
var namePath = (0, _valueUtil.getNamePath)(name);
var fieldError = _this.getFieldsError([namePath])[0];
return fieldError.warnings;
});
(0, _defineProperty2.default)(this, "isFieldsTouched", function () {
_this.warningUnhooked();
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var arg0 = args[0],
arg1 = args[1];
var namePathList;
var isAllFieldsTouched = false;
if (args.length === 0) {
namePathList = null;
} else if (args.length === 1) {
if (Array.isArray(arg0)) {
namePathList = arg0.map(_valueUtil.getNamePath);
isAllFieldsTouched = false;
} else {
namePathList = null;
isAllFieldsTouched = arg0;
}
} else {
namePathList = arg0.map(_valueUtil.getNamePath);
isAllFieldsTouched = arg1;
}
var fieldEntities = _this.getFieldEntities(true);
var isFieldTouched = function isFieldTouched(field) {
return field.isFieldTouched();
};
// ===== Will get fully compare when not config namePathList =====
if (!namePathList) {
return isAllFieldsTouched ? fieldEntities.every(function (entity) {
return isFieldTouched(entity) || entity.isList();
}) : fieldEntities.some(isFieldTouched);
}
// Generate a nest tree for validate
var map = new _NameMap.default();
namePathList.forEach(function (shortNamePath) {
map.set(shortNamePath, []);
});
fieldEntities.forEach(function (field) {
var fieldNamePath = field.getNamePath();
// Find matched entity and put into list
namePathList.forEach(function (shortNamePath) {
if (shortNamePath.every(function (nameUnit, i) {
return fieldNamePath[i] === nameUnit;
})) {
map.update(shortNamePath, function (list) {
return [].concat((0, _toConsumableArray2.default)(list), [field]);
});
}
});
});
// Check if NameMap value is touched
var isNamePathListTouched = function isNamePathListTouched(entities) {
return entities.some(isFieldTouched);
};
var namePathListEntities = map.map(function (_ref4) {
var value = _ref4.value;
return value;
});
return isAllFieldsTouched ? namePathListEntities.every(isNamePathListTouched) : namePathListEntities.some(isNamePathListTouched);
});
(0, _defineProperty2.default)(this, "isFieldTouched", function (name) {
_this.warningUnhooked();
return _this.isFieldsTouched([name]);
});
(0, _defineProperty2.default)(this, "isFieldsValidating", function (nameList) {
_this.warningUnhooked();
var fieldEntities = _this.getFieldEntities();
if (!nameList) {
return fieldEntities.some(function (testField) {
return testField.isFieldValidating();
});
}
var namePathList = nameList.map(_valueUtil.getNamePath);
return fieldEntities.some(function (testField) {
var fieldNamePath = testField.getNamePath();
return (0, _valueUtil.containsNamePath)(namePathList, fieldNamePath) && testField.isFieldValidating();
});
});
(0, _defineProperty2.default)(this, "isFieldValidating", function (name) {
_this.warningUnhooked();
return _this.isFieldsValidating([name]);
});
/**
* Reset Field with field `initialValue` prop.
* Can pass `entities` or `namePathList` or just nothing.
*/
(0, _defineProperty2.default)(this, "resetWithFieldInitialValue", function () {
var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// Create cache
var cache = new _NameMap.default();
var fieldEntities = _this.getFieldEntities(true);
fieldEntities.forEach(function (field) {
var initialValue = field.props.initialValue;
var namePath = field.getNamePath();
// Record only if has `initialValue`
if (initialValue !== undefined) {
var records = cache.get(namePath) || new Set();
records.add({
entity: field,
value: initialValue
});
cache.set(namePath, records);
}
});
// Reset
var resetWithFields = function resetWithFields(entities) {
entities.forEach(function (field) {
var initialValue = field.props.initialValue;
if (initialValue !== undefined) {
var namePath = field.getNamePath();
var formInitialValue = _this.getInitialValue(namePath);
if (formInitialValue !== undefined) {
// Warning if conflict with form initialValues and do not modify value
(0, _warning.default)(false, "Form already set 'initialValues' with path '".concat(namePath.join('.'), "'. Field can not overwrite it."));
} else {
var records = cache.get(namePath);
if (records && records.size > 1) {
// Warning if multiple field set `initialValue`and do not modify value
(0, _warning.default)(false, "Multiple Field with path '".concat(namePath.join('.'), "' set 'initialValue'. Can not decide which one to pick."));
} else if (records) {
var originValue = _this.getFieldValue(namePath);
var isListField = field.isListField();
// Set `initialValue`
if (!isListField && (!info.skipExist || originValue === undefined)) {
_this.updateStore((0, _valueUtil.setValue)(_this.store, namePath, (0, _toConsumableArray2.default)(records)[0].value));
}
}
}
}
});
};
var requiredFieldEntities;
if (info.entities) {
requiredFieldEntities = info.entities;
} else if (info.namePathList) {
requiredFieldEntities = [];
info.namePathList.forEach(function (namePath) {
var records = cache.get(namePath);
if (records) {
var _requiredFieldEntitie;
(_requiredFieldEntitie = requiredFieldEntities).push.apply(_requiredFieldEntitie, (0, _toConsumableArray2.default)((0, _toConsumableArray2.default)(records).map(function (r) {
return r.entity;
})));
}
});
} else {
requiredFieldEntities = fieldEntities;
}
resetWithFields(requiredFieldEntities);
});
(0, _defineProperty2.default)(this, "resetFields", function (nameList) {
_this.warningUnhooked();
var prevStore = _this.store;
if (!nameList) {
_this.updateStore((0, _set.merge)(_this.initialValues));
_this.resetWithFieldInitialValue();
_this.notifyObservers(prevStore, null, {
type: 'reset'
});
_this.notifyWatch();
return;
}
// Reset by `nameList`
var namePathList = nameList.map(_valueUtil.getNamePath);
namePathList.forEach(function (namePath) {
var initialValue = _this.getInitialValue(namePath);
_this.updateStore((0, _valueUtil.setValue)(_this.store, namePath, initialValue));
});
_this.resetWithFieldInitialValue({
namePathList: namePathList
});
_this.notifyObservers(prevStore, namePathList, {
type: 'reset'
});
_this.notifyWatch(namePathList);
});
(0, _defineProperty2.default)(this, "setFields", function (fields) {
_this.warningUnhooked();
var prevStore = _this.store;
var namePathList = [];
fields.forEach(function (fieldData) {
var name = fieldData.name,
data = (0, _objectWithoutProperties2.default)(fieldData, _excluded);
var namePath = (0, _valueUtil.getNamePath)(name);
namePathList.push(namePath);
// Value
if ('value' in data) {
_this.updateStore((0, _valueUtil.setValue)(_this.store, namePath, data.value));
}
_this.notifyObservers(prevStore, [namePath], {
type: 'setField',
data: fieldData
});
});
_this.notifyWatch(namePathList);
});
(0, _defineProperty2.default)(this, "getFields", function () {
var entities = _this.getFieldEntities(true);
var fields = entities.map(function (field) {
var namePath = field.getNamePath();
var meta = field.getMeta();
var fieldData = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, meta), {}, {
name: namePath,
value: _this.getFieldValue(namePath)
});
Object.defineProperty(fieldData, 'originRCField', {
value: true
});
return fieldData;
});
return fields;
});
// =========================== Observer ===========================
/**
* This only trigger when a field is on constructor to avoid we get initialValue too late
*/
(0, _defineProperty2.default)(this, "initEntityValue", function (entity) {
var initialValue = entity.props.initialValue;
if (initialValue !== undefined) {
var namePath = entity.getNamePath();
var prevValue = (0, _valueUtil.getValue)(_this.store, namePath);
if (prevValue === undefined) {
_this.updateStore((0, _valueUtil.setValue)(_this.store, namePath, initialValue));
}
}
});
(0, _defineProperty2.default)(this, "isMergedPreserve", function (fieldPreserve) {
var mergedPreserve = fieldPreserve !== undefined ? fieldPreserve : _this.preserve;
return mergedPreserve !== null && mergedPreserve !== void 0 ? mergedPreserve : true;
});
(0, _defineProperty2.default)(this, "registerField", function (entity) {
_this.fieldEntities.push(entity);
var namePath = entity.getNamePath();
_this.notifyWatch([namePath]);
// Set initial values
if (entity.props.initialValue !== undefined) {
var prevStore = _this.store;
_this.resetWithFieldInitialValue({
entities: [entity],
skipExist: true
});
_this.notifyObservers(prevStore, [entity.getNamePath()], {
type: 'valueUpdate',
source: 'internal'
});
}
// un-register field callback
return function (isListField, preserve) {
var subNamePath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
_this.fieldEntities = _this.fieldEntities.filter(function (item) {
return item !== entity;
});
// Clean up store value if not preserve
if (!_this.isMergedPreserve(preserve) && (!isListField || subNamePath.length > 1)) {
var defaultValue = isListField ? undefined : _this.getInitialValue(namePath);
if (namePath.length && _this.getFieldValue(namePath) !== defaultValue && _this.fieldEntities.every(function (field) {
return (
// Only reset when no namePath exist
!(0, _valueUtil.matchNamePath)(field.getNamePath(), namePath)
);
})) {
var _prevStore = _this.store;
_this.updateStore((0, _valueUtil.setValue)(_prevStore, namePath, defaultValue, true));
// Notify that field is unmount
_this.notifyObservers(_prevStore, [namePath], {
type: 'remove'
});
// Dependencies update
_this.triggerDependenciesUpdate(_prevStore, namePath);
}
}
_this.notifyWatch([namePath]);
};
});
(0, _defineProperty2.default)(this, "dispatch", function (action) {
switch (action.type) {
case 'updateValue':
{
var namePath = action.namePath,
value = action.value;
_this.updateValue(namePath, value);
break;
}
case 'validateField':
{
var _namePath = action.namePath,
triggerName = action.triggerName;
_this.validateFields([_namePath], {
triggerName: triggerName
});
break;
}
default:
// Currently we don't have other action. Do nothing.
}
});
(0, _defineProperty2.default)(this, "notifyObservers", function (prevStore, namePathList, info) {
if (_this.subscribable) {
var mergedInfo = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, info), {}, {
store: _this.getFieldsValue(true)
});
_this.getFieldEntities().forEach(function (_ref5) {
var onStoreChange = _ref5.onStoreChange;
onStoreChange(prevStore, namePathList, mergedInfo);
});
} else {
_this.forceRootUpdate();
}
});
/**
* Notify dependencies children with parent update
* We need delay to trigger validate in case Field is under render props
*/
(0, _defineProperty2.default)(this, "triggerDependenciesUpdate", function (prevStore, namePath) {
var childrenFields = _this.getDependencyChildrenFields(namePath);
if (childrenFields.length) {
_this.validateFields(childrenFields);
}
_this.notifyObservers(prevStore, childrenFields, {
type: 'dependenciesUpdate',
relatedFields: [namePath].concat((0, _toConsumableArray2.default)(childrenFields))
});
return childrenFields;
});
(0, _defineProperty2.default)(this, "updateValue", function (name, value) {
var namePath = (0, _valueUtil.getNamePath)(name);
var prevStore = _this.store;
_this.updateStore((0, _valueUtil.setValue)(_this.store, namePath, value));
_this.notifyObservers(prevStore, [namePath], {
type: 'valueUpdate',
source: 'internal'
});
_this.notifyWatch([namePath]);
// Dependencies update
var childrenFields = _this.triggerDependenciesUpdate(prevStore, namePath);
// trigger callback function
var onValuesChange = _this.callbacks.onValuesChange;
if (onValuesChange) {
var changedValues = (0, _valueUtil.cloneByNamePathList)(_this.store, [namePath]);
onValuesChange(changedValues, _this.getFieldsValue());
}
_this.triggerOnFieldsChange([namePath].concat((0, _toConsumableArray2.default)(childrenFields)));
});
// Let all child Field get update.
(0, _defineProperty2.default)(this, "setFieldsValue", function (store) {
_this.warningUnhooked();
var prevStore = _this.store;
if (store) {
var nextStore = (0, _set.merge)(_this.store, store);
_this.updateStore(nextStore);
}
_this.notifyObservers(prevStore, null, {
type: 'valueUpdate',
source: 'external'
});
_this.notifyWatch();
});
(0, _defineProperty2.default)(this, "setFieldValue", function (name, value) {
_this.setFields([{
name: name,
value: value,
errors: [],
warnings: []
}]);
});
(0, _defineProperty2.default)(this, "getDependencyChildrenFields", function (rootNamePath) {
var children = new Set();
var childrenFields = [];
var dependencies2fields = new _NameMap.default();
/**
* Generate maps
* Can use cache to save perf if user report performance issue with this
*/
_this.getFieldEntities().forEach(function (field) {
var dependencies = field.props.dependencies;
(dependencies || []).forEach(function (dependency) {
var dependencyNamePath = (0, _valueUtil.getNamePath)(dependency);
dependencies2fields.update(dependencyNamePath, function () {
var fields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Set();
fields.add(field);
return fields;
});
});
});
var fillChildren = function fillChildren(namePath) {
var fields = dependencies2fields.get(namePath) || new Set();
fields.forEach(function (field) {
if (!children.has(field)) {
children.add(field);
var fieldNamePath = field.getNamePath();
if (field.isFieldDirty() && fieldNamePath.length) {
childrenFields.push(fieldNamePath);
fillChildren(fieldNamePath);
}
}
});
};
fillChildren(rootNamePath);
return childrenFields;
});
(0, _defineProperty2.default)(this, "triggerOnFieldsChange", function (namePathList, filedErrors) {
var onFieldsChange = _this.callbacks.onFieldsChange;
if (onFieldsChange) {
var fields = _this.getFields();
/**
* Fill errors since `fields` may be replaced by controlled fields
*/
if (filedErrors) {
var cache = new _NameMap.default();
filedErrors.forEach(function (_ref6) {
var name = _ref6.name,
errors = _ref6.errors;
cache.set(name, errors);
});
fields.forEach(function (field) {
// eslint-disable-next-line no-param-reassign
field.errors = cache.get(field.name) || field.errors;
});
}
var changedFields = fields.filter(function (_ref7) {
var fieldName = _ref7.name;
return (0, _valueUtil.containsNamePath)(namePathList, fieldName);
});
if (changedFields.length) {
onFieldsChange(changedFields, fields);
}
}
});
// =========================== Validate ===========================
(0, _defineProperty2.default)(this, "validateFields", function (arg1, arg2) {
_this.warningUnhooked();
var nameList;
var options;
if (Array.isArray(arg1) || typeof arg1 === 'string' || typeof arg2 === 'string') {
nameList = arg1;
options = arg2;
} else {
options = arg1;
}
var provideNameList = !!nameList;
var namePathList = provideNameList ? nameList.map(_valueUtil.getNamePath) : [];
// Collect result in promise list
var promiseList = [];
// We temp save the path which need trigger for `onFieldsChange`
var TMP_SPLIT = String(Date.now());
var validateNamePathList = new Set();
var _ref8 = options || {},
recursive = _ref8.recursive,
dirty = _ref8.dirty;
_this.getFieldEntities(true).forEach(function (field) {
// Add field if not provide `nameList`
if (!provideNameList) {
namePathList.push(field.getNamePath());
}
// Skip if without rule
if (!field.props.rules || !field.props.rules.length) {
return;
}
// Skip if only validate dirty field
if (dirty && !field.isFieldDirty()) {
return;
}
var fieldNamePath = field.getNamePath();
validateNamePathList.add(fieldNamePath.join(TMP_SPLIT));
// Add field validate rule in to promise list
if (!provideNameList || (0, _valueUtil.containsNamePath)(namePathList, fieldNamePath, recursive)) {
var promise = field.validateRules((0, _objectSpread2.default)({
validateMessages: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _messages.defaultValidateMessages), _this.validateMessages)
}, options));
// Wrap promise with field
promiseList.push(promise.then(function () {
return {
name: fieldNamePath,
errors: [],
warnings: []
};
}).catch(function (ruleErrors) {
var _ruleErrors$forEach;
var mergedErrors = [];
var mergedWarnings = [];
(_ruleErrors$forEach = ruleErrors.forEach) === null || _ruleErrors$forEach === void 0 || _ruleErrors$forEach.call(ruleErrors, function (_ref9) {
var warningOnly = _ref9.rule.warningOnly,
errors = _ref9.errors;
if (warningOnly) {
mergedWarnings.push.apply(mergedWarnings, (0, _toConsumableArray2.default)(errors));
} else {
mergedErrors.push.apply(mergedErrors, (0, _toConsumableArray2.default)(errors));
}
});
if (mergedErrors.length) {
return Promise.reject({
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings
});
}
return {
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings
};
}));
}
});
var summaryPromise = (0, _asyncUtil.allPromiseFinish)(promiseList);
_this.lastValidatePromise = summaryPromise;
// Notify fields with rule that validate has finished and need update
summaryPromise.catch(function (results) {
return results;
}).then(function (results) {
var resultNamePathList = results.map(function (_ref10) {
var name = _ref10.name;
return name;
});
_this.notifyObservers(_this.store, resultNamePathList, {
type: 'validateFinish'
});
_this.triggerOnFieldsChange(resultNamePathList, results);
});
var returnPromise = summaryPromise.then(function () {
if (_this.lastValidatePromise === summaryPromise) {
return Promise.resolve(_this.getFieldsValue(namePathList));
}
return Promise.reject([]);
}).catch(function (results) {
var errorList = results.filter(function (result) {
return result && result.errors.length;
});
return Promise.reject({
values: _this.getFieldsValue(namePathList),
errorFields: errorList,
outOfDate: _this.lastValidatePromise !== summaryPromise
});
});
// Do not throw in console
returnPromise.catch(function (e) {
return e;
});
// `validating` changed. Trigger `onFieldsChange`
var triggerNamePathList = namePathList.filter(function (namePath) {
return validateNamePathList.has(namePath.join(TMP_SPLIT));
});
_this.triggerOnFieldsChange(triggerNamePathList);
return returnPromise;
});
// ============================ Submit ============================
(0, _defineProperty2.default)(this, "submit", function () {
_this.warningUnhooked();
_this.validateFields().then(function (values) {
var onFinish = _this.callbacks.onFinish;
if (onFinish) {
try {
onFinish(values);
} catch (err) {
// Should print error if user `onFinish` callback failed
console.error(err);
}
}
}).catch(function (e) {
var onFinishFailed = _this.callbacks.onFinishFailed;
if (onFinishFailed) {
onFinishFailed(e);
}
});
});
this.forceRootUpdate = forceRootUpdate;
});
function useForm(form) {
var formRef = React.useRef();
var _React$useState = React.useState({}),
_React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
forceUpdate = _React$useState2[1];
if (!formRef.current) {
if (form) {
formRef.current = form;
} else {
// Create a new FormStore if not provided
var forceReRender = function forceReRender() {
forceUpdate({});
};
var formStore = new FormStore(forceReRender);
formRef.current = formStore.getForm();
}
}
return [formRef.current];
}
var _default = exports.default = useForm;

14
node_modules/rc-field-form/lib/useWatch.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import type { FormInstance, NamePath, Store, WatchOptions } from './interface';
type ReturnPromise<T> = T extends Promise<infer ValueType> ? ValueType : never;
type GetGeneric<TForm extends FormInstance> = ReturnPromise<ReturnType<TForm['validateFields']>>;
export declare function stringify(value: any): string | number;
declare function useWatch<TDependencies1 extends keyof GetGeneric<TForm>, TForm extends FormInstance, TDependencies2 extends keyof GetGeneric<TForm>[TDependencies1], TDependencies3 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2], TDependencies4 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3]>(dependencies: [TDependencies1, TDependencies2, TDependencies3, TDependencies4], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3][TDependencies4];
declare function useWatch<TDependencies1 extends keyof GetGeneric<TForm>, TForm extends FormInstance, TDependencies2 extends keyof GetGeneric<TForm>[TDependencies1], TDependencies3 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2]>(dependencies: [TDependencies1, TDependencies2, TDependencies3], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3];
declare function useWatch<TDependencies1 extends keyof GetGeneric<TForm>, TForm extends FormInstance, TDependencies2 extends keyof GetGeneric<TForm>[TDependencies1]>(dependencies: [TDependencies1, TDependencies2], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies1][TDependencies2];
declare function useWatch<TDependencies extends keyof GetGeneric<TForm>, TForm extends FormInstance>(dependencies: TDependencies | [TDependencies], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>[TDependencies];
declare function useWatch<TForm extends FormInstance>(dependencies: [], form?: TForm | WatchOptions<TForm>): GetGeneric<TForm>;
declare function useWatch<TForm extends FormInstance, TSelected = unknown>(selector: (values: GetGeneric<TForm>) => TSelected, form?: TForm | WatchOptions<TForm>): TSelected;
declare function useWatch<ValueType = Store, TSelected = unknown>(selector: (values: ValueType) => TSelected, form?: FormInstance | WatchOptions<FormInstance>): TSelected;
declare function useWatch<TForm extends FormInstance>(dependencies: NamePath, form?: TForm | WatchOptions<TForm>): any;
declare function useWatch<ValueType = Store>(dependencies: NamePath, form?: FormInstance | WatchOptions<FormInstance>): ValueType;
export default useWatch;

104
node_modules/rc-field-form/lib/useWatch.js generated vendored Normal file
View File

@@ -0,0 +1,104 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.stringify = stringify;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
var _react = require("react");
var _FieldContext = _interopRequireWildcard(require("./FieldContext"));
var _typeUtil = require("./utils/typeUtil");
var _valueUtil = require("./utils/valueUtil");
function stringify(value) {
try {
return JSON.stringify(value);
} catch (err) {
return Math.random();
}
}
var useWatchWarning = process.env.NODE_ENV !== 'production' ? function (namePath) {
var fullyStr = namePath.join('__RC_FIELD_FORM_SPLIT__');
var nameStrRef = (0, _react.useRef)(fullyStr);
(0, _warning.default)(nameStrRef.current === fullyStr, '`useWatch` is not support dynamic `namePath`. Please provide static instead.');
} : function () {};
// ------- selector type -------
// ------- selector type end -------
function useWatch() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var dependencies = args[0],
_args$ = args[1],
_form = _args$ === void 0 ? {} : _args$;
var options = (0, _typeUtil.isFormInstance)(_form) ? {
form: _form
} : _form;
var form = options.form;
var _useState = (0, _react.useState)(),
_useState2 = (0, _slicedToArray2.default)(_useState, 2),
value = _useState2[0],
setValue = _useState2[1];
var valueStr = (0, _react.useMemo)(function () {
return stringify(value);
}, [value]);
var valueStrRef = (0, _react.useRef)(valueStr);
valueStrRef.current = valueStr;
var fieldContext = (0, _react.useContext)(_FieldContext.default);
var formInstance = form || fieldContext;
var isValidForm = formInstance && formInstance._init;
// Warning if not exist form instance
if (process.env.NODE_ENV !== 'production') {
(0, _warning.default)(args.length === 2 ? form ? isValidForm : true : isValidForm, 'useWatch requires a form instance since it can not auto detect from context.');
}
var namePath = (0, _valueUtil.getNamePath)(dependencies);
var namePathRef = (0, _react.useRef)(namePath);
namePathRef.current = namePath;
useWatchWarning(namePath);
(0, _react.useEffect)(function () {
// Skip if not exist form instance
if (!isValidForm) {
return;
}
var getFieldsValue = formInstance.getFieldsValue,
getInternalHooks = formInstance.getInternalHooks;
var _getInternalHooks = getInternalHooks(_FieldContext.HOOK_MARK),
registerWatch = _getInternalHooks.registerWatch;
var getWatchValue = function getWatchValue(values, allValues) {
var watchValue = options.preserve ? allValues : values;
return typeof dependencies === 'function' ? dependencies(watchValue) : (0, _valueUtil.getValue)(watchValue, namePathRef.current);
};
var cancelRegister = registerWatch(function (values, allValues) {
var newValue = getWatchValue(values, allValues);
var nextValueStr = stringify(newValue);
// Compare stringify in case it's nest object
if (valueStrRef.current !== nextValueStr) {
valueStrRef.current = nextValueStr;
setValue(newValue);
}
});
// TODO: We can improve this perf in future
var initialValue = getWatchValue(getFieldsValue(), getFieldsValue(true));
// React 18 has the bug that will queue update twice even the value is not changed
// ref: https://github.com/facebook/react/issues/27213
if (value !== initialValue) {
setValue(initialValue);
}
return cancelRegister;
},
// We do not need re-register since namePath content is the same
// eslint-disable-next-line react-hooks/exhaustive-deps
[isValidForm]);
return value;
}
var _default = exports.default = useWatch;

18
node_modules/rc-field-form/lib/utils/NameMap.d.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import type { InternalNamePath } from '../interface';
interface KV<T> {
key: InternalNamePath;
value: T;
}
/**
* NameMap like a `Map` but accepts `string[]` as key.
*/
declare class NameMap<T> {
private kvs;
set(key: InternalNamePath, value: T): void;
get(key: InternalNamePath): T;
update(key: InternalNamePath, updater: (origin: T) => T | null): void;
delete(key: InternalNamePath): void;
map<U>(callback: (kv: KV<T>) => U): U[];
toJSON(): Record<string, T>;
}
export default NameMap;

98
node_modules/rc-field-form/lib/utils/NameMap.js generated vendored Normal file
View File

@@ -0,0 +1,98 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var SPLIT = '__@field_split__';
/**
* Convert name path into string to fast the fetch speed of Map.
*/
function normalize(namePath) {
return namePath.map(function (cell) {
return "".concat((0, _typeof2.default)(cell), ":").concat(cell);
})
// Magic split
.join(SPLIT);
}
/**
* NameMap like a `Map` but accepts `string[]` as key.
*/
var NameMap = /*#__PURE__*/function () {
function NameMap() {
(0, _classCallCheck2.default)(this, NameMap);
(0, _defineProperty2.default)(this, "kvs", new Map());
}
(0, _createClass2.default)(NameMap, [{
key: "set",
value: function set(key, value) {
this.kvs.set(normalize(key), value);
}
}, {
key: "get",
value: function get(key) {
return this.kvs.get(normalize(key));
}
}, {
key: "update",
value: function update(key, updater) {
var origin = this.get(key);
var next = updater(origin);
if (!next) {
this.delete(key);
} else {
this.set(key, next);
}
}
}, {
key: "delete",
value: function _delete(key) {
this.kvs.delete(normalize(key));
}
// Since we only use this in test, let simply realize this
}, {
key: "map",
value: function map(callback) {
return (0, _toConsumableArray2.default)(this.kvs.entries()).map(function (_ref) {
var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
key = _ref2[0],
value = _ref2[1];
var cells = key.split(SPLIT);
return callback({
key: cells.map(function (cell) {
var _cell$match = cell.match(/^([^:]*):(.*)$/),
_cell$match2 = (0, _slicedToArray2.default)(_cell$match, 3),
type = _cell$match2[1],
unit = _cell$match2[2];
return type === 'number' ? Number(unit) : unit;
}),
value: value
});
});
}
}, {
key: "toJSON",
value: function toJSON() {
var json = {};
this.map(function (_ref3) {
var key = _ref3.key,
value = _ref3.value;
json[key.join('.')] = value;
return null;
});
return json;
}
}]);
return NameMap;
}();
var _default = exports.default = NameMap;

2
node_modules/rc-field-form/lib/utils/asyncUtil.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import type { FieldError } from '../interface';
export declare function allPromiseFinish(promiseList: Promise<FieldError>[]): Promise<FieldError[]>;

32
node_modules/rc-field-form/lib/utils/asyncUtil.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.allPromiseFinish = allPromiseFinish;
function allPromiseFinish(promiseList) {
var hasError = false;
var count = promiseList.length;
var results = [];
if (!promiseList.length) {
return Promise.resolve([]);
}
return new Promise(function (resolve, reject) {
promiseList.forEach(function (promise, index) {
promise.catch(function (e) {
hasError = true;
return e;
}).then(function (result) {
count -= 1;
results[index] = result;
if (count > 0) {
return;
}
if (hasError) {
reject(results);
}
resolve(results);
});
});
});
}

47
node_modules/rc-field-form/lib/utils/messages.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
export declare const defaultValidateMessages: {
default: string;
required: string;
enum: string;
whitespace: string;
date: {
format: string;
parse: string;
invalid: string;
};
types: {
string: string;
method: string;
array: string;
object: string;
number: string;
date: string;
boolean: string;
integer: string;
float: string;
regexp: string;
email: string;
url: string;
hex: string;
};
string: {
len: string;
min: string;
max: string;
range: string;
};
number: {
len: string;
min: string;
max: string;
range: string;
};
array: {
len: string;
min: string;
max: string;
range: string;
};
pattern: {
mismatch: string;
};
};

54
node_modules/rc-field-form/lib/utils/messages.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.defaultValidateMessages = void 0;
var typeTemplate = "'${name}' is not a valid ${type}";
var defaultValidateMessages = exports.defaultValidateMessages = {
default: "Validation error on field '${name}'",
required: "'${name}' is required",
enum: "'${name}' must be one of [${enum}]",
whitespace: "'${name}' cannot be empty",
date: {
format: "'${name}' is invalid for format date",
parse: "'${name}' could not be parsed as date",
invalid: "'${name}' is invalid date"
},
types: {
string: typeTemplate,
method: typeTemplate,
array: typeTemplate,
object: typeTemplate,
number: typeTemplate,
date: typeTemplate,
boolean: typeTemplate,
integer: typeTemplate,
float: typeTemplate,
regexp: typeTemplate,
email: typeTemplate,
url: typeTemplate,
hex: typeTemplate
},
string: {
len: "'${name}' must be exactly ${len} characters",
min: "'${name}' must be at least ${min} characters",
max: "'${name}' cannot be longer than ${max} characters",
range: "'${name}' must be between ${min} and ${max} characters"
},
number: {
len: "'${name}' must equal ${len}",
min: "'${name}' cannot be less than ${min}",
max: "'${name}' cannot be greater than ${max}",
range: "'${name}' must be between ${min} and ${max}"
},
array: {
len: "'${name}' must be exactly ${len} in length",
min: "'${name}' cannot be less than ${min} in length",
max: "'${name}' cannot be greater than ${max} in length",
range: "'${name}' must be between ${min} and ${max} in length"
},
pattern: {
mismatch: "'${name}' does not match pattern ${pattern}"
}
};

3
node_modules/rc-field-form/lib/utils/typeUtil.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { FormInstance } from '../interface';
export declare function toArray<T>(value?: T | T[] | null): T[];
export declare function isFormInstance<T>(form: T | FormInstance): form is FormInstance;

16
node_modules/rc-field-form/lib/utils/typeUtil.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isFormInstance = isFormInstance;
exports.toArray = toArray;
function toArray(value) {
if (value === undefined || value === null) {
return [];
}
return Array.isArray(value) ? value : [value];
}
function isFormInstance(form) {
return form && !!form._init;
}

View File

@@ -0,0 +1,6 @@
import type { InternalNamePath, InternalValidateOptions, RuleObject, StoreValue, RuleError } from '../interface';
/**
* We use `async-validator` to validate the value.
* But only check one value in a time to avoid namePath validate issue.
*/
export declare function validateRules(namePath: InternalNamePath, value: StoreValue, rules: RuleObject[], options: InternalValidateOptions, validateFirst: boolean | 'parallel', messageVariables?: Record<string, string>): Promise<RuleError[]>;

320
node_modules/rc-field-form/lib/utils/validateUtil.js generated vendored Normal file
View File

@@ -0,0 +1,320 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validateRules = validateRules;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/regeneratorRuntime"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _asyncValidator = _interopRequireDefault(require("@rc-component/async-validator"));
var React = _interopRequireWildcard(require("react"));
var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
var _messages = require("./messages");
var _set = require("rc-util/lib/utils/set");
// Remove incorrect original ts define
var AsyncValidator = _asyncValidator.default;
/**
* Replace with template.
* `I'm ${name}` + { name: 'bamboo' } = I'm bamboo
*/
function replaceMessage(template, kv) {
return template.replace(/\\?\$\{\w+\}/g, function (str) {
if (str.startsWith('\\')) {
return str.slice(1);
}
var key = str.slice(2, -1);
return kv[key];
});
}
var CODE_LOGIC_ERROR = 'CODE_LOGIC_ERROR';
function validateRule(_x, _x2, _x3, _x4, _x5) {
return _validateRule.apply(this, arguments);
}
/**
* We use `async-validator` to validate the value.
* But only check one value in a time to avoid namePath validate issue.
*/
function _validateRule() {
_validateRule = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee2(name, value, rule, options, messageVariables) {
var cloneRule, originValidator, subRuleField, validator, messages, result, subResults, kv, fillVariableResult;
return (0, _regeneratorRuntime2.default)().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
cloneRule = (0, _objectSpread2.default)({}, rule); // Bug of `async-validator`
// https://github.com/react-component/field-form/issues/316
// https://github.com/react-component/field-form/issues/313
delete cloneRule.ruleIndex;
// https://github.com/ant-design/ant-design/issues/40497#issuecomment-1422282378
AsyncValidator.warning = function () {
return void 0;
};
if (cloneRule.validator) {
originValidator = cloneRule.validator;
cloneRule.validator = function () {
try {
return originValidator.apply(void 0, arguments);
} catch (error) {
console.error(error);
return Promise.reject(CODE_LOGIC_ERROR);
}
};
}
// We should special handle array validate
subRuleField = null;
if (cloneRule && cloneRule.type === 'array' && cloneRule.defaultField) {
subRuleField = cloneRule.defaultField;
delete cloneRule.defaultField;
}
validator = new AsyncValidator((0, _defineProperty2.default)({}, name, [cloneRule]));
messages = (0, _set.merge)(_messages.defaultValidateMessages, options.validateMessages);
validator.messages(messages);
result = [];
_context2.prev = 10;
_context2.next = 13;
return Promise.resolve(validator.validate((0, _defineProperty2.default)({}, name, value), (0, _objectSpread2.default)({}, options)));
case 13:
_context2.next = 18;
break;
case 15:
_context2.prev = 15;
_context2.t0 = _context2["catch"](10);
if (_context2.t0.errors) {
result = _context2.t0.errors.map(function (_ref4, index) {
var message = _ref4.message;
var mergedMessage = message === CODE_LOGIC_ERROR ? messages.default : message;
return /*#__PURE__*/React.isValidElement(mergedMessage) ?
/*#__PURE__*/
// Wrap ReactNode with `key`
React.cloneElement(mergedMessage, {
key: "error_".concat(index)
}) : mergedMessage;
});
}
case 18:
if (!(!result.length && subRuleField && Array.isArray(value) && value.length > 0)) {
_context2.next = 23;
break;
}
_context2.next = 21;
return Promise.all(value.map(function (subValue, i) {
return validateRule("".concat(name, ".").concat(i), subValue, subRuleField, options, messageVariables);
}));
case 21:
subResults = _context2.sent;
return _context2.abrupt("return", subResults.reduce(function (prev, errors) {
return [].concat((0, _toConsumableArray2.default)(prev), (0, _toConsumableArray2.default)(errors));
}, []));
case 23:
// Replace message with variables
kv = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, rule), {}, {
name: name,
enum: (rule.enum || []).join(', ')
}, messageVariables);
fillVariableResult = result.map(function (error) {
if (typeof error === 'string') {
return replaceMessage(error, kv);
}
return error;
});
return _context2.abrupt("return", fillVariableResult);
case 26:
case "end":
return _context2.stop();
}
}, _callee2, null, [[10, 15]]);
}));
return _validateRule.apply(this, arguments);
}
function validateRules(namePath, value, rules, options, validateFirst, messageVariables) {
var name = namePath.join('.');
// Fill rule with context
var filledRules = rules.map(function (currentRule, ruleIndex) {
var originValidatorFunc = currentRule.validator;
var cloneRule = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, currentRule), {}, {
ruleIndex: ruleIndex
});
// Replace validator if needed
if (originValidatorFunc) {
cloneRule.validator = function (rule, val, callback) {
var hasPromise = false;
// Wrap callback only accept when promise not provided
var wrappedCallback = function wrappedCallback() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Wait a tick to make sure return type is a promise
Promise.resolve().then(function () {
(0, _warning.default)(!hasPromise, 'Your validator function has already return a promise. `callback` will be ignored.');
if (!hasPromise) {
callback.apply(void 0, args);
}
});
};
// Get promise
var promise = originValidatorFunc(rule, val, wrappedCallback);
hasPromise = promise && typeof promise.then === 'function' && typeof promise.catch === 'function';
/**
* 1. Use promise as the first priority.
* 2. If promise not exist, use callback with warning instead
*/
(0, _warning.default)(hasPromise, '`callback` is deprecated. Please return a promise instead.');
if (hasPromise) {
promise.then(function () {
callback();
}).catch(function (err) {
callback(err || ' ');
});
}
};
}
return cloneRule;
}).sort(function (_ref, _ref2) {
var w1 = _ref.warningOnly,
i1 = _ref.ruleIndex;
var w2 = _ref2.warningOnly,
i2 = _ref2.ruleIndex;
if (!!w1 === !!w2) {
// Let keep origin order
return i1 - i2;
}
if (w1) {
return 1;
}
return -1;
});
// Do validate rules
var summaryPromise;
if (validateFirst === true) {
// >>>>> Validate by serialization
summaryPromise = new Promise( /*#__PURE__*/function () {
var _ref3 = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee(resolve, reject) {
var i, rule, errors;
return (0, _regeneratorRuntime2.default)().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
i = 0;
case 1:
if (!(i < filledRules.length)) {
_context.next = 12;
break;
}
rule = filledRules[i];
_context.next = 5;
return validateRule(name, value, rule, options, messageVariables);
case 5:
errors = _context.sent;
if (!errors.length) {
_context.next = 9;
break;
}
reject([{
errors: errors,
rule: rule
}]);
return _context.abrupt("return");
case 9:
i += 1;
_context.next = 1;
break;
case 12:
/* eslint-enable */
resolve([]);
case 13:
case "end":
return _context.stop();
}
}, _callee);
}));
return function (_x6, _x7) {
return _ref3.apply(this, arguments);
};
}());
} else {
// >>>>> Validate by parallel
var rulePromises = filledRules.map(function (rule) {
return validateRule(name, value, rule, options, messageVariables).then(function (errors) {
return {
errors: errors,
rule: rule
};
});
});
summaryPromise = (validateFirst ? finishOnFirstFailed(rulePromises) : finishOnAllFailed(rulePromises)).then(function (errors) {
// Always change to rejection for Field to catch
return Promise.reject(errors);
});
}
// Internal catch error to avoid console error log.
summaryPromise.catch(function (e) {
return e;
});
return summaryPromise;
}
function finishOnAllFailed(_x8) {
return _finishOnAllFailed.apply(this, arguments);
}
function _finishOnAllFailed() {
_finishOnAllFailed = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee3(rulePromises) {
return (0, _regeneratorRuntime2.default)().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", Promise.all(rulePromises).then(function (errorsList) {
var _ref5;
var errors = (_ref5 = []).concat.apply(_ref5, (0, _toConsumableArray2.default)(errorsList));
return errors;
}));
case 1:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return _finishOnAllFailed.apply(this, arguments);
}
function finishOnFirstFailed(_x9) {
return _finishOnFirstFailed.apply(this, arguments);
}
function _finishOnFirstFailed() {
_finishOnFirstFailed = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee4(rulePromises) {
var count;
return (0, _regeneratorRuntime2.default)().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
count = 0;
return _context4.abrupt("return", new Promise(function (resolve) {
rulePromises.forEach(function (promise) {
promise.then(function (ruleError) {
if (ruleError.errors.length) {
resolve([ruleError]);
}
count += 1;
if (count === rulePromises.length) {
resolve([]);
}
});
});
}));
case 2:
case "end":
return _context4.stop();
}
}, _callee4);
}));
return _finishOnFirstFailed.apply(this, arguments);
}

41
node_modules/rc-field-form/lib/utils/valueUtil.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import getValue from 'rc-util/lib/utils/get';
import setValue from 'rc-util/lib/utils/set';
import type { InternalNamePath, NamePath, Store, EventArgs } from '../interface';
export { getValue, setValue };
/**
* Convert name to internal supported format.
* This function should keep since we still thinking if need support like `a.b.c` format.
* 'a' => ['a']
* 123 => [123]
* ['a', 123] => ['a', 123]
*/
export declare function getNamePath(path: NamePath | null): InternalNamePath;
export declare function cloneByNamePathList(store: Store, namePathList: InternalNamePath[]): Store;
/**
* Check if `namePathList` includes `namePath`.
* @param namePathList A list of `InternalNamePath[]`
* @param namePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
export declare function containsNamePath(namePathList: InternalNamePath[], namePath: InternalNamePath, partialMatch?: boolean): boolean;
/**
* Check if `namePath` is super set or equal of `subNamePath`.
* @param namePath A list of `InternalNamePath[]`
* @param subNamePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
export declare function matchNamePath(namePath: InternalNamePath, subNamePath: InternalNamePath | null, partialMatch?: boolean): boolean;
type SimilarObject = string | number | object;
export declare function isSimilar(source: SimilarObject, target: SimilarObject): boolean;
export declare function defaultGetValueFromEvent(valuePropName: string, ...args: EventArgs): any;
/**
* Moves an array item from one position in an array to another.
*
* Note: This is a pure function so a new array will be returned, instead
* of altering the array argument.
*
* @param array Array in which to move an item. (required)
* @param moveIndex The index of the item to move. (required)
* @param toIndex The index to move item at moveIndex to. (required)
*/
export declare function move<T>(array: T[], moveIndex: number, toIndex: number): T[];

140
node_modules/rc-field-form/lib/utils/valueUtil.js generated vendored Normal file
View File

@@ -0,0 +1,140 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cloneByNamePathList = cloneByNamePathList;
exports.containsNamePath = containsNamePath;
exports.defaultGetValueFromEvent = defaultGetValueFromEvent;
exports.getNamePath = getNamePath;
Object.defineProperty(exports, "getValue", {
enumerable: true,
get: function get() {
return _get.default;
}
});
exports.isSimilar = isSimilar;
exports.matchNamePath = matchNamePath;
exports.move = move;
Object.defineProperty(exports, "setValue", {
enumerable: true,
get: function get() {
return _set.default;
}
});
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _get = _interopRequireDefault(require("rc-util/lib/utils/get"));
var _set = _interopRequireDefault(require("rc-util/lib/utils/set"));
var _typeUtil = require("./typeUtil");
/**
* Convert name to internal supported format.
* This function should keep since we still thinking if need support like `a.b.c` format.
* 'a' => ['a']
* 123 => [123]
* ['a', 123] => ['a', 123]
*/
function getNamePath(path) {
return (0, _typeUtil.toArray)(path);
}
function cloneByNamePathList(store, namePathList) {
var newStore = {};
namePathList.forEach(function (namePath) {
var value = (0, _get.default)(store, namePath);
newStore = (0, _set.default)(newStore, namePath, value);
});
return newStore;
}
/**
* Check if `namePathList` includes `namePath`.
* @param namePathList A list of `InternalNamePath[]`
* @param namePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
function containsNamePath(namePathList, namePath) {
var partialMatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return namePathList && namePathList.some(function (path) {
return matchNamePath(namePath, path, partialMatch);
});
}
/**
* Check if `namePath` is super set or equal of `subNamePath`.
* @param namePath A list of `InternalNamePath[]`
* @param subNamePath Compare `InternalNamePath`
* @param partialMatch True will make `[a, b]` match `[a, b, c]`
*/
function matchNamePath(namePath, subNamePath) {
var partialMatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!namePath || !subNamePath) {
return false;
}
if (!partialMatch && namePath.length !== subNamePath.length) {
return false;
}
return subNamePath.every(function (nameUnit, i) {
return namePath[i] === nameUnit;
});
}
// Like `shallowEqual`, but we not check the data which may cause re-render
function isSimilar(source, target) {
if (source === target) {
return true;
}
if (!source && target || source && !target) {
return false;
}
if (!source || !target || (0, _typeof2.default)(source) !== 'object' || (0, _typeof2.default)(target) !== 'object') {
return false;
}
var sourceKeys = Object.keys(source);
var targetKeys = Object.keys(target);
var keys = new Set([].concat(sourceKeys, targetKeys));
return (0, _toConsumableArray2.default)(keys).every(function (key) {
var sourceValue = source[key];
var targetValue = target[key];
if (typeof sourceValue === 'function' && typeof targetValue === 'function') {
return true;
}
return sourceValue === targetValue;
});
}
function defaultGetValueFromEvent(valuePropName) {
var event = arguments.length <= 1 ? undefined : arguments[1];
if (event && event.target && (0, _typeof2.default)(event.target) === 'object' && valuePropName in event.target) {
return event.target[valuePropName];
}
return event;
}
/**
* Moves an array item from one position in an array to another.
*
* Note: This is a pure function so a new array will be returned, instead
* of altering the array argument.
*
* @param array Array in which to move an item. (required)
* @param moveIndex The index of the item to move. (required)
* @param toIndex The index to move item at moveIndex to. (required)
*/
function move(array, moveIndex, toIndex) {
var length = array.length;
if (moveIndex < 0 || moveIndex >= length || toIndex < 0 || toIndex >= length) {
return array;
}
var item = array[moveIndex];
var diff = moveIndex - toIndex;
if (diff > 0) {
// move left
return [].concat((0, _toConsumableArray2.default)(array.slice(0, toIndex)), [item], (0, _toConsumableArray2.default)(array.slice(toIndex, moveIndex)), (0, _toConsumableArray2.default)(array.slice(moveIndex + 1, length)));
}
if (diff < 0) {
// move right
return [].concat((0, _toConsumableArray2.default)(array.slice(0, moveIndex)), (0, _toConsumableArray2.default)(array.slice(moveIndex + 1, toIndex + 1)), [item], (0, _toConsumableArray2.default)(array.slice(toIndex + 1, length)));
}
return array;
}

84
node_modules/rc-field-form/package.json generated vendored Normal file
View File

@@ -0,0 +1,84 @@
{
"name": "rc-field-form",
"version": "2.7.1",
"description": "React Form Component",
"typings": "es/index.d.ts",
"engines": {
"node": ">=8.x"
},
"keywords": [
"react",
"react-component",
"react-form",
"form"
],
"homepage": "https://github.com/react-component/field-form",
"author": "smith3816@gmail.com",
"repository": {
"type": "git",
"url": "https://github.com/react-component/field-form.git"
},
"bugs": {
"url": "https://github.com/react-component/field-form/issues"
},
"files": [
"lib",
"es",
"dist",
"assets/*.css"
],
"license": "MIT",
"main": "./lib/index",
"module": "./es/index",
"scripts": {
"start": "dumi dev",
"docs:build": "dumi build",
"docs:deploy": "gh-pages -d docs-dist",
"compile": "father build",
"deploy": "npm run docs:build && npm run docs:deploy",
"prettier": "prettier --write \"**/*.{js,jsx,tsx,ts,less,md,json}\"",
"test": "rc-test",
"test:coverage": "umi-test --coverage",
"prepublishOnly": "npm run compile && np --no-cleanup --yolo --no-publish --branch=antd-5.x",
"lint": "eslint src/ --ext .tsx,.ts",
"lint:tsc": "tsc -p tsconfig.json --noEmit",
"now-build": "npm run docs:build"
},
"peerDependencies": {
"react": ">=16.9.0",
"react-dom": ">=16.9.0"
},
"dependencies": {
"@babel/runtime": "^7.18.0",
"@rc-component/async-validator": "^5.0.3",
"rc-util": "^5.32.2"
},
"devDependencies": {
"@rc-component/father-plugin": "^1.0.0",
"@testing-library/jest-dom": "^6.1.4",
"@testing-library/react": "^16.0.0",
"@types/jest": "^29.2.5",
"@types/lodash": "^4.14.135",
"@types/node": "^22.0.2",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"@umijs/fabric": "^4.0.1",
"dumi": "^2.0.0",
"eslint": "^8.54.0",
"eslint-plugin-jest": "^27.6.0",
"eslint-plugin-unicorn": "^56.0.1",
"father": "^4.0.0",
"gh-pages": "^6.1.0",
"jest": "^29.0.0",
"np": "^10.0.2",
"prettier": "^3.1.0",
"rc-test": "^7.0.15",
"react": "^18.0.0",
"react-dnd": "^8.0.3",
"react-dnd-html5-backend": "^8.0.3",
"react-dom": "^18.0.0",
"react-redux": "^9.0.4",
"redux": "^5.0.0",
"typescript": "^5.1.6"
}
}