Latest updates from IceHrmPro

This commit is contained in:
Thilina Pituwala
2020-05-20 18:47:29 +02:00
parent 60c92d7935
commit 7453a58aad
18012 changed files with 2089245 additions and 10173 deletions

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

@@ -0,0 +1,36 @@
import * as React from 'react';
import { FormInstance, InternalNamePath, Meta, NamePath, Rule, Store, StoreValue, EventArgs } from './interface';
export declare type ShouldUpdate = true | ((prevValues: Store, nextValues: Store, info: {
source?: string;
}) => boolean);
interface ChildProps {
[name: string]: any;
}
export interface InternalFieldProps {
children?: React.ReactElement | ((control: ChildProps, meta: Meta, form: FormInstance) => 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;
trigger?: string;
validateTrigger?: string | string[] | false;
validateFirst?: boolean;
valuePropName?: string;
messageVariables?: Record<string, string>;
onReset?: () => void;
}
export interface FieldProps extends Omit<InternalFieldProps, 'name'> {
name?: NamePath;
}
export interface FieldState {
resetCount: number;
}
declare const WrapperField: React.FC<FieldProps>;
export default WrapperField;

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

@@ -0,0 +1,479 @@
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
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 _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import toChildrenArray from "rc-util/es/Children/toArray";
import warning from "rc-util/es/warning";
import * as React from 'react';
import FieldContext, { HOOK_MARK } from './FieldContext';
import { toArray } from './utils/typeUtil';
import { validateRules } from './utils/validateUtil';
import { containsNamePath, defaultGetValueFromEvent, getNamePath, getValue } from './utils/valueUtil';
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;
} // 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);
function Field() {
var _this;
_classCallCheck(this, Field);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Field).apply(this, arguments));
_this.state = {
resetCount: 0
};
_this.cancelRegisterFunc = null;
_this.destroy = 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.
*/
_this.touched = false;
_this.validatePromise = null;
_this.errors = [];
_this.cancelRegister = function () {
if (_this.cancelRegisterFunc) {
_this.cancelRegisterFunc();
}
_this.cancelRegisterFunc = null;
}; // ================================== Utils ==================================
_this.getNamePath = function () {
var name = _this.props.name;
var _this$context$prefixN = _this.context.prefixName,
prefixName = _this$context$prefixN === void 0 ? [] : _this$context$prefixN;
return name !== undefined ? [].concat(_toConsumableArray(prefixName), _toConsumableArray(name)) : [];
};
_this.getRules = function () {
var _this$props$rules = _this.props.rules,
rules = _this$props$rules === void 0 ? [] : _this$props$rules;
return rules.map(function (rule) {
if (typeof rule === 'function') {
return rule(_this.context);
}
return rule;
});
};
_this.refresh = function () {
if (_this.destroy) return;
/**
* Clean up current node.
*/
_this.setState(function (_ref) {
var resetCount = _ref.resetCount;
return {
resetCount: resetCount + 1
};
});
}; // ========================= Field Entity Interfaces =========================
// Trigger by store update. Check if need update the component
_this.onStoreChange = function (prevStore, namePathList, info) {
var _this$props = _this.props,
shouldUpdate = _this$props.shouldUpdate,
_this$props$dependenc = _this$props.dependencies,
dependencies = _this$props$dependenc === void 0 ? [] : _this$props$dependenc,
onReset = _this$props.onReset;
var getFieldsValue = _this.context.getFieldsValue;
var values = getFieldsValue(true);
var namePath = _this.getNamePath();
var prevValue = _this.getValue(prevStore);
var curValue = _this.getValue();
var namePathMatch = namePathList && containsNamePath(namePathList, namePath); // `setFieldsValue` is a quick access to update related status
if (info.type === 'valueUpdate' && info.source === 'external' && prevValue !== curValue) {
_this.touched = true;
_this.validatePromise = null;
_this.errors = [];
}
switch (info.type) {
case 'reset':
if (!namePathList || namePathMatch) {
// Clean up state
_this.touched = false;
_this.validatePromise = null;
_this.errors = [];
if (onReset) {
onReset();
}
_this.refresh();
return;
}
break;
case 'setField':
{
if (namePathMatch) {
var data = info.data;
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 || [];
}
_this.reRender();
return;
} // Handle update by `setField` with `shouldUpdate`
if (shouldUpdate && !namePath.length && requireUpdate(shouldUpdate, prevStore, values, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
case 'dependenciesUpdate':
{
/**
* Trigger when marked `dependencies` updated. Related fields will all update
*/
var dependencyList = dependencies.map(getNamePath);
if (namePathMatch || dependencyList.some(function (dependency) {
return containsNamePath(info.relatedFields, dependency);
})) {
_this.reRender();
return;
}
break;
}
default:
/**
* - If `namePath` exists in `namePathList`, means it's related value and should update.
* - If `dependencies` exists in `namePathList`, means upstream trigger update.
* - If `shouldUpdate` provided, use customize logic to update the field
* - else to check if value changed
*/
if (namePathMatch || dependencies.some(function (dependency) {
return containsNamePath(namePathList, getNamePath(dependency));
}) || requireUpdate(shouldUpdate, prevStore, values, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
if (shouldUpdate === true) {
_this.reRender();
}
};
_this.validateRules = function (options) {
var _this$props2 = _this.props,
_this$props2$validate = _this$props2.validateFirst,
validateFirst = _this$props2$validate === void 0 ? false : _this$props2$validate,
messageVariables = _this$props2.messageVariables;
var _ref2 = options || {},
triggerName = _ref2.triggerName;
var namePath = _this.getNamePath();
var filteredRules = _this.getRules();
if (triggerName) {
filteredRules = filteredRules.filter(function (rule) {
var validateTrigger = rule.validateTrigger;
if (!validateTrigger) {
return true;
}
var triggerList = toArray(validateTrigger);
return triggerList.includes(triggerName);
});
}
var promise = validateRules(namePath, _this.getValue(), filteredRules, options, validateFirst, messageVariables);
_this.validatePromise = promise;
_this.errors = [];
promise.catch(function (e) {
return e;
}).then(function () {
var errors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
if (_this.validatePromise === promise) {
_this.validatePromise = null;
_this.errors = errors;
_this.reRender();
}
});
return promise;
};
_this.isFieldValidating = function () {
return !!_this.validatePromise;
};
_this.isFieldTouched = function () {
return _this.touched;
};
_this.getErrors = function () {
return _this.errors;
}; // ============================= Child Component =============================
_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,
name: _this.getNamePath()
};
return meta;
}; // Only return validate child node. If invalidate, will do nothing about field.
_this.getOnlyChild = function (children) {
// Support render props
if (typeof children === 'function') {
var meta = _this.getMeta();
return _objectSpread({}, _this.getOnlyChild(children(_this.getControlled(), meta, _this.context)), {
isFunction: true
});
} // Filed element only
var childList = toChildrenArray(children);
if (childList.length !== 1 || !React.isValidElement(childList[0])) {
return {
child: childList,
isFunction: false
};
}
return {
child: childList[0],
isFunction: false
};
}; // ============================== Field Control ==============================
_this.getValue = function (store) {
var getFieldsValue = _this.context.getFieldsValue;
var namePath = _this.getNamePath();
return getValue(store || getFieldsValue(true), namePath);
};
_this.getControlled = function () {
var childProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _this$props3 = _this.props,
trigger = _this$props3.trigger,
validateTrigger = _this$props3.validateTrigger,
getValueFromEvent = _this$props3.getValueFromEvent,
normalize = _this$props3.normalize,
valuePropName = _this$props3.valuePropName;
var namePath = _this.getNamePath();
var _this$context = _this.context,
getInternalHooks = _this$context.getInternalHooks,
getFieldsValue = _this$context.getFieldsValue;
var _getInternalHooks = getInternalHooks(HOOK_MARK),
dispatch = _getInternalHooks.dispatch;
var value = _this.getValue(); // eslint-disable-next-line @typescript-eslint/no-explicit-any
var originTriggerFunc = childProps[trigger];
var control = _objectSpread({}, childProps, _defineProperty({}, valuePropName, value)); // Add trigger
control[trigger] = function () {
// Mark as touched
_this.touched = true;
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));
}
dispatch({
type: 'updateValue',
namePath: namePath,
value: newValue
});
if (originTriggerFunc) {
originTriggerFunc.apply(void 0, args);
}
}; // Add validateTrigger
var validateTriggerList = toArray(validateTrigger || []);
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;
};
return _this;
} // ============================== Subscriptions ==============================
_createClass(Field, [{
key: "componentDidMount",
value: function componentDidMount() {
var getInternalHooks = this.context.getInternalHooks;
var _getInternalHooks2 = getInternalHooks(HOOK_MARK),
registerField = _getInternalHooks2.registerField;
this.cancelRegisterFunc = registerField(this);
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.cancelRegister();
this.destroy = true;
}
}, {
key: "reRender",
value: function reRender() {
if (this.destroy) 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 (React.isValidElement(child)) {
returnChildNode = React.cloneElement(child, this.getControlled(child.props));
} else {
warning(!child, '`children` of Field is not validate ReactElement.');
returnChildNode = child;
}
return React.createElement(React.Fragment, {
key: resetCount
}, returnChildNode);
}
}]);
return Field;
}(React.Component);
Field.contextType = FieldContext;
Field.defaultProps = {
trigger: 'onChange',
validateTrigger: 'onChange',
valuePropName: 'value'
};
var WrapperField = function WrapperField(_ref3) {
var name = _ref3.name,
restProps = _objectWithoutProperties(_ref3, ["name"]);
var namePath = name !== undefined ? getNamePath(name) : undefined;
return React.createElement(Field, Object.assign({
key: "_".concat((namePath || []).join('_')),
name: namePath
}, restProps));
};
export default WrapperField;

5
web/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 { InternalFormInstance } from './interface';
export declare const HOOK_MARK = "RC_FORM_INTERNAL_HOOKS";
declare const Context: React.Context<InternalFormInstance>;
export default Context;

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

@@ -0,0 +1,36 @@
import * as React from 'react';
import warning from 'warning';
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 = React.createContext({
getFieldValue: warningFunc,
getFieldsValue: warningFunc,
getFieldError: warningFunc,
getFieldsError: warningFunc,
isFieldsTouched: warningFunc,
isFieldTouched: warningFunc,
isFieldValidating: warningFunc,
isFieldsValidating: warningFunc,
resetFields: warningFunc,
setFields: warningFunc,
setFieldsValue: warningFunc,
validateFields: warningFunc,
submit: warningFunc,
getInternalHooks: function getInternalHooks() {
warningFunc();
return {
dispatch: warningFunc,
registerField: warningFunc,
useSubscribe: warningFunc,
setInitialValues: warningFunc,
setCallbacks: warningFunc,
getFields: warningFunc,
setValidateMessages: warningFunc
};
}
});
export default Context;

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

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

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

@@ -0,0 +1,123 @@
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import * as React from 'react';
import useForm from './useForm';
import FieldContext, { HOOK_MARK } from './FieldContext';
import FormContext from './FormContext';
import { isSimilar } from './utils/valueUtil';
var Form = function Form(_ref, ref) {
var name = _ref.name,
initialValues = _ref.initialValues,
fields = _ref.fields,
form = _ref.form,
children = _ref.children,
_ref$component = _ref.component,
Component = _ref$component === void 0 ? 'form' : _ref$component,
validateMessages = _ref.validateMessages,
onValuesChange = _ref.onValuesChange,
_onFieldsChange = _ref.onFieldsChange,
_onFinish = _ref.onFinish,
onFinishFailed = _ref.onFinishFailed,
restProps = _objectWithoutProperties(_ref, ["name", "initialValues", "fields", "form", "children", "component", "validateMessages", "onValuesChange", "onFieldsChange", "onFinish", "onFinishFailed"]);
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 _formInstance$getInte = formInstance.getInternalHooks(HOOK_MARK),
useSubscribe = _formInstance$getInte.useSubscribe,
setInitialValues = _formInstance$getInte.setInitialValues,
setCallbacks = _formInstance$getInte.setCallbacks,
setValidateMessages = _formInstance$getInte.setValidateMessages; // Pass ref with form instance
React.useImperativeHandle(ref, function () {
return formInstance;
}); // 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({}, 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
}); // Set initial value, init store value when first mount
var mountRef = React.useRef(null);
setInitialValues(initialValues, !mountRef.current);
if (!mountRef.current) {
mountRef.current = true;
} // Prepare children by `children` type
var childrenNode = children;
var childrenRenderProps = typeof children === 'function';
if (childrenRenderProps) {
var values = formInstance.getFieldsValue(true);
childrenNode = children(values, formInstance);
} // 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 wrapperNode = React.createElement(FieldContext.Provider, {
value: formInstance
}, childrenNode);
if (Component === false) {
return wrapperNode;
}
return React.createElement(Component, Object.assign({}, restProps, {
onSubmit: function onSubmit(event) {
event.preventDefault();
event.stopPropagation();
formInstance.submit();
}
}), wrapperNode);
};
export default Form;

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

@@ -0,0 +1,28 @@
import * as React from 'react';
import { ValidateMessages, FormInstance, FieldData, Store } from './interface';
export interface Forms {
[name: 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;
}
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;

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

@@ -0,0 +1,67 @@
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import * as React from 'react';
var FormContext = 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 React.createElement(FormContext.Provider, {
value: _objectSpread({}, formContext, {
validateMessages: _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({}, 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;

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

@@ -0,0 +1,17 @@
import * as React from 'react';
import { NamePath, StoreValue } from './interface';
interface ListField {
name: number;
key: number;
}
interface ListOperations {
add: (defaultValue?: StoreValue) => void;
remove: (index: number) => void;
move: (from: number, to: number) => void;
}
interface ListProps {
name: NamePath;
children?: (fields: ListField[], operations: ListOperations) => JSX.Element | React.ReactNode;
}
declare const List: React.FunctionComponent<ListProps>;
export default List;

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

@@ -0,0 +1,126 @@
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import * as React from 'react';
import warning from 'warning';
import FieldContext from './FieldContext';
import Field from './Field';
import { move as _move, getNamePath } from './utils/valueUtil';
var List = function List(_ref) {
var name = _ref.name,
children = _ref.children;
var context = React.useContext(FieldContext);
var keyRef = React.useRef({
keys: [],
id: 0
});
var keyManager = keyRef.current; // User should not pass `children` as other type.
if (typeof children !== 'function') {
warning(false, 'Form.List only accepts function as children.');
return null;
}
var parentPrefixName = getNamePath(context.prefixName) || [];
var prefixName = [].concat(_toConsumableArray(parentPrefixName), _toConsumableArray(getNamePath(name)));
var shouldUpdate = function shouldUpdate(prevValue, nextValue, _ref2) {
var source = _ref2.source;
if (source === 'internal') {
return false;
}
return prevValue !== nextValue;
};
return React.createElement(FieldContext.Provider, {
value: _objectSpread({}, context, {
prefixName: prefixName
})
}, React.createElement(Field, {
name: [],
shouldUpdate: shouldUpdate
}, function (_ref3) {
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) {
// Mapping keys
keyManager.keys = [].concat(_toConsumableArray(keyManager.keys), [keyManager.id]);
keyManager.id += 1;
var newValue = getNewValue();
onChange([].concat(_toConsumableArray(newValue), [defaultValue]));
},
remove: function remove(index) {
var newValue = getNewValue(); // Do not handle out of range
if (index < 0 || index >= newValue.length) {
return;
} // Update key mapping
var newKeys = keyManager.keys.map(function (key, id) {
if (id < index) {
return key;
}
return keyManager.keys[id + 1];
});
keyManager.keys = newKeys.slice(0, -1); // Trigger store change
onChange(newValue.filter(function (_, id) {
return id !== index;
}));
},
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));
}
};
return children(value.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
};
}), operations);
}));
};
export default List;

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

@@ -0,0 +1,18 @@
import * as React from 'react';
import { FormInstance } from './interface';
import Field from './Field';
import List from './List';
import useForm from './useForm';
import { FormProps } from './Form';
import { FormProvider } from './FormContext';
declare const InternalForm: React.ForwardRefExoticComponent<FormProps & React.RefAttributes<FormInstance>>;
declare type InternalForm = typeof InternalForm;
interface RefForm extends InternalForm {
FormProvider: typeof FormProvider;
Field: typeof Field;
List: typeof List;
useForm: typeof useForm;
}
declare const RefForm: RefForm;
export { FormInstance, Field, List, useForm, FormProvider };
export default RefForm;

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

@@ -0,0 +1,14 @@
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';
var InternalForm = React.forwardRef(FieldForm);
var RefForm = InternalForm;
RefForm.FormProvider = FormProvider;
RefForm.Field = Field;
RefForm.List = List;
RefForm.useForm = useForm;
export { Field, List, useForm, FormProvider };
export default RefForm;

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

@@ -0,0 +1,190 @@
import { ReactElement } from 'react';
import { ReducerAction } from './useForm';
export declare type InternalNamePath = (string | number)[];
export declare type NamePath = string | number | InternalNamePath;
export declare type StoreValue = any;
export interface Store {
[name: string]: StoreValue;
}
export interface Meta {
touched: boolean;
validating: boolean;
errors: string[];
name: InternalNamePath;
}
export interface InternalFieldData extends Meta {
value: StoreValue;
}
/**
* Used by `setFields` config
*/
export interface FieldData extends Partial<Omit<InternalFieldData, 'name'>> {
name: NamePath;
}
export declare type RuleType = 'string' | 'number' | 'boolean' | 'method' | 'regexp' | 'integer' | 'float' | 'object' | 'enum' | 'date' | 'url' | 'hex' | 'email';
declare type Validator = (rule: RuleObject, value: StoreValue, callback: (error?: string) => void) => Promise<void> | void;
export declare type RuleRender = (form: FormInstance) => RuleObject;
interface BaseRule {
enum?: StoreValue[];
len?: number;
max?: number;
message?: string | ReactElement;
min?: number;
pattern?: RegExp;
required?: boolean;
transform?: (value: StoreValue) => StoreValue;
type?: RuleType;
validator?: Validator;
whitespace?: boolean;
/** Customize rule level `validateTrigger`. Must be subset of Field `validateTrigger` */
validateTrigger?: string | string[];
}
interface ArrayRule extends Omit<BaseRule, 'type'> {
type: 'array';
defaultField?: RuleObject;
}
export declare type RuleObject = BaseRule | ArrayRule;
export declare type Rule = RuleObject | RuleRender;
export interface ValidateErrorEntity {
values: Store;
errorFields: {
name: InternalNamePath;
errors: string[];
}[];
outOfDate: boolean;
}
export interface FieldEntity {
onStoreChange: (store: Store, namePathList: InternalNamePath[] | null, info: NotifyInfo) => void;
isFieldTouched: () => boolean;
isFieldValidating: () => boolean;
validateRules: (options?: ValidateOptions) => Promise<string[]>;
getMeta: () => Meta;
getNamePath: () => InternalNamePath;
getErrors: () => string[];
props: {
name?: NamePath;
rules?: Rule[];
dependencies?: NamePath[];
};
}
export interface FieldError {
name: InternalNamePath;
errors: string[];
}
export interface ValidateOptions {
triggerName?: string;
validateMessages?: ValidateMessages;
}
export declare type InternalValidateFields = (nameList?: NamePath[], options?: ValidateOptions) => Promise<Store>;
export declare type ValidateFields = (nameList?: NamePath[]) => Promise<Store>;
interface ValueUpdateInfo {
type: 'valueUpdate';
source: 'internal' | 'external';
}
export declare type NotifyInfo = ValueUpdateInfo | {
type: 'validateFinish' | 'reset';
} | {
type: 'setField';
data: FieldData;
} | {
type: 'dependenciesUpdate';
/**
* Contains all the related `InternalNamePath[]`.
* a <- b <- c : change `a`
* relatedFields=[a, b, c]
*/
relatedFields: InternalNamePath[];
};
export interface Callbacks {
onValuesChange?: (changedValues: Store, values: Store) => void;
onFieldsChange?: (changedFields: FieldData[], allFields: FieldData[]) => void;
onFinish?: (values: Store) => void;
onFinishFailed?: (errorInfo: ValidateErrorEntity) => void;
}
export interface InternalHooks {
dispatch: (action: ReducerAction) => void;
registerField: (entity: FieldEntity) => () => void;
useSubscribe: (subscribable: boolean) => void;
setInitialValues: (values: Store, init: boolean) => void;
setCallbacks: (callbacks: Callbacks) => void;
getFields: (namePathList?: InternalNamePath[]) => FieldData[];
setValidateMessages: (validateMessages: ValidateMessages) => void;
}
export interface FormInstance {
getFieldValue: (name: NamePath) => StoreValue;
getFieldsValue: (nameList?: NamePath[] | true, filterFunc?: (meta: Meta) => boolean) => Store;
getFieldError: (name: NamePath) => string[];
getFieldsError: (nameList?: NamePath[]) => FieldError[];
isFieldsTouched(nameList?: NamePath[], allFieldsTouched?: boolean): boolean;
isFieldsTouched(allFieldsTouched?: boolean): boolean;
isFieldTouched: (name: NamePath) => boolean;
isFieldValidating: (name: NamePath) => boolean;
isFieldsValidating: (nameList: NamePath[]) => boolean;
resetFields: (fields?: NamePath[]) => void;
setFields: (fields: FieldData[]) => void;
setFieldsValue: (value: Store) => void;
validateFields: ValidateFields;
submit: () => void;
}
export declare type InternalFormInstance = Omit<FormInstance, 'validateFields'> & {
validateFields: InternalValidateFields;
/**
* Passed by field context props
*/
prefixName?: InternalNamePath;
/**
* 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;
};
export declare type EventArgs = any[];
declare 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 {};

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

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

@@ -0,0 +1,64 @@
import { InternalNamePath, FormInstance, InternalFormInstance, StoreValue } from './interface';
interface UpdateAction {
type: 'updateValue';
namePath: InternalNamePath;
value: StoreValue;
}
interface ValidateAction {
type: 'validateField';
namePath: InternalNamePath;
triggerName: string;
}
export declare 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 lastValidatePromise;
constructor(forceRootUpdate: () => void);
getForm: () => InternalFormInstance;
private getInternalHooks;
private useSubscribe;
/**
* First time `setInitialValues` should update store with initial value
*/
private setInitialValues;
private getInitialValue;
private setCallbacks;
private setValidateMessages;
private warningUnhooked;
/**
* 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 isFieldsTouched;
private isFieldTouched;
private isFieldsValidating;
private isFieldValidating;
private resetFields;
private setFields;
private getFields;
private registerField;
private dispatch;
private notifyObservers;
private updateValue;
private setFieldsValue;
private getDependencyChildrenFields;
private triggerOnFieldsChange;
private validateFields;
private submit;
}
declare function useForm(form?: FormInstance): [FormInstance];
export default useForm;

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

@@ -0,0 +1,655 @@
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import * as React from 'react';
import warning from 'warning';
import { HOOK_MARK } from './FieldContext';
import { allPromiseFinish } from './utils/asyncUtil';
import NameMap from './utils/NameMap';
import { defaultValidateMessages } from './utils/messages';
import { cloneByNamePathList, containsNamePath, getNamePath, getValue, setValue, setValues } from './utils/valueUtil';
export var FormStore = function FormStore(forceRootUpdate) {
var _this = this;
_classCallCheck(this, FormStore);
this.formHooked = false;
this.subscribable = true;
this.store = {};
this.fieldEntities = [];
this.initialValues = {};
this.callbacks = {};
this.validateMessages = null;
this.lastValidatePromise = null;
this.getForm = function () {
return {
getFieldValue: _this.getFieldValue,
getFieldsValue: _this.getFieldsValue,
getFieldError: _this.getFieldError,
getFieldsError: _this.getFieldsError,
isFieldsTouched: _this.isFieldsTouched,
isFieldTouched: _this.isFieldTouched,
isFieldValidating: _this.isFieldValidating,
isFieldsValidating: _this.isFieldsValidating,
resetFields: _this.resetFields,
setFields: _this.setFields,
setFieldsValue: _this.setFieldsValue,
validateFields: _this.validateFields,
submit: _this.submit,
getInternalHooks: _this.getInternalHooks
};
}; // ======================== Internal Hooks ========================
this.getInternalHooks = function (key) {
if (key === HOOK_MARK) {
_this.formHooked = true;
return {
dispatch: _this.dispatch,
registerField: _this.registerField,
useSubscribe: _this.useSubscribe,
setInitialValues: _this.setInitialValues,
setCallbacks: _this.setCallbacks,
setValidateMessages: _this.setValidateMessages,
getFields: _this.getFields
};
}
warning(false, '`getInternalHooks` is internal usage. Should not call directly.');
return null;
};
this.useSubscribe = function (subscribable) {
_this.subscribable = subscribable;
};
/**
* First time `setInitialValues` should update store with initial value
*/
this.setInitialValues = function (initialValues, init) {
_this.initialValues = initialValues || {};
if (init) {
_this.store = setValues({}, initialValues, _this.store);
}
};
this.getInitialValue = function (namePath) {
return getValue(_this.initialValues, namePath);
};
this.setCallbacks = function (callbacks) {
_this.callbacks = callbacks;
};
this.setValidateMessages = function (validateMessages) {
_this.validateMessages = validateMessages;
};
this.warningUnhooked = function () {
if (process.env.NODE_ENV !== 'production' && !_this.formHooked) {
warning(false, 'Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop?');
}
}; // ============================ Fields ============================
/**
* Get registered field entities.
* @param pure Only return field which has a `name`. Default: false
*/
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;
});
};
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;
};
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)
};
});
};
this.getFieldsValue = function (nameList, filterFunc) {
_this.warningUnhooked();
if (nameList === true && !filterFunc) {
return _this.store;
}
var fieldEntities = _this.getFieldEntitiesForNamePathList(Array.isArray(nameList) ? nameList : null);
var filteredNameList = [];
fieldEntities.forEach(function (entity) {
var namePath = 'INVALIDATE_NAME_PATH' in entity ? entity.INVALIDATE_NAME_PATH : entity.getNamePath();
if (!filterFunc) {
filteredNameList.push(namePath);
} else {
var meta = 'getMeta' in entity ? entity.getMeta() : null;
if (filterFunc(meta)) {
filteredNameList.push(namePath);
}
}
});
return cloneByNamePathList(_this.store, filteredNameList.map(getNamePath));
};
this.getFieldValue = function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
return getValue(_this.store, namePath);
};
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()
};
}
return {
name: getNamePath(nameList[index]),
errors: []
};
});
};
this.getFieldError = function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
var fieldError = _this.getFieldsError([namePath])[0];
return fieldError.errors;
};
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 testTouched = function testTouched(field) {
// Not provide `nameList` will check all the fields
if (!namePathList) {
return field.isFieldTouched();
}
var fieldNamePath = field.getNamePath();
if (containsNamePath(namePathList, fieldNamePath)) {
return field.isFieldTouched();
}
return isAllFieldsTouched;
};
return isAllFieldsTouched ? _this.getFieldEntities(true).every(testTouched) : _this.getFieldEntities(true).some(testTouched);
};
this.isFieldTouched = function (name) {
_this.warningUnhooked();
return _this.isFieldsTouched([name]);
};
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();
});
};
this.isFieldValidating = function (name) {
_this.warningUnhooked();
return _this.isFieldsValidating([name]);
};
this.resetFields = function (nameList) {
_this.warningUnhooked();
var prevStore = _this.store;
if (!nameList) {
_this.store = setValues({}, _this.initialValues);
_this.notifyObservers(prevStore, null, {
type: 'reset'
});
return;
} // Reset by `nameList`
var namePathList = nameList.map(getNamePath);
namePathList.forEach(function (namePath) {
var initialValue = _this.getInitialValue(namePath);
_this.store = setValue(_this.store, namePath, initialValue);
});
_this.notifyObservers(prevStore, namePathList, {
type: 'reset'
});
};
this.setFields = function (fields) {
_this.warningUnhooked();
var prevStore = _this.store;
fields.forEach(function (fieldData) {
var name = fieldData.name,
errors = fieldData.errors,
data = _objectWithoutProperties(fieldData, ["name", "errors"]);
var namePath = getNamePath(name); // Value
if ('value' in data) {
_this.store = setValue(_this.store, namePath, data.value);
}
_this.notifyObservers(prevStore, [namePath], {
type: 'setField',
data: fieldData
});
});
};
this.getFields = function () {
return _this.getFieldEntities(true).map(function (field) {
var namePath = field.getNamePath();
var meta = field.getMeta();
var fieldData = _objectSpread({}, meta, {
name: namePath,
value: _this.getFieldValue(namePath)
});
Object.defineProperty(fieldData, 'originRCField', {
value: true
});
return fieldData;
});
}; // =========================== Observer ===========================
this.registerField = function (entity) {
_this.fieldEntities.push(entity);
return function () {
_this.fieldEntities = _this.fieldEntities.filter(function (item) {
return item !== entity;
});
};
};
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.
}
};
this.notifyObservers = function (prevStore, namePathList, info) {
if (_this.subscribable) {
_this.getFieldEntities().forEach(function (_ref) {
var onStoreChange = _ref.onStoreChange;
onStoreChange(prevStore, namePathList, info);
});
} else {
_this.forceRootUpdate();
}
};
this.updateValue = function (name, value) {
var namePath = getNamePath(name);
var prevStore = _this.store;
_this.store = setValue(_this.store, namePath, value);
_this.notifyObservers(prevStore, [namePath], {
type: 'valueUpdate',
source: 'internal'
}); // Notify dependencies children with parent update
var childrenFields = _this.getDependencyChildrenFields(namePath);
_this.validateFields(childrenFields);
_this.notifyObservers(prevStore, childrenFields, {
type: 'dependenciesUpdate',
relatedFields: [namePath].concat(_toConsumableArray(childrenFields))
}); // trigger callback function
var onValuesChange = _this.callbacks.onValuesChange;
if (onValuesChange) {
var changedValues = cloneByNamePathList(_this.store, [namePath]);
onValuesChange(changedValues, _this.store);
}
_this.triggerOnFieldsChange([namePath].concat(_toConsumableArray(childrenFields)));
}; // Let all child Field get update.
this.setFieldsValue = function (store) {
_this.warningUnhooked();
var prevStore = _this.store;
if (store) {
_this.store = setValues(_this.store, store);
}
_this.notifyObservers(prevStore, null, {
type: 'valueUpdate',
source: 'external'
});
};
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.isFieldTouched() && fieldNamePath.length) {
childrenFields.push(fieldNamePath);
fillChildren(fieldNamePath);
}
}
});
};
fillChildren(rootNamePath);
return childrenFields;
};
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 (_ref2) {
var name = _ref2.name,
errors = _ref2.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 (_ref3) {
var fieldName = _ref3.name;
return containsNamePath(namePathList, fieldName);
});
onFieldsChange(changedFields, fields);
}
}; // =========================== Validate ===========================
this.validateFields = function (nameList, options) {
_this.warningUnhooked();
var provideNameList = !!nameList;
var namePathList = provideNameList ? nameList.map(getNamePath) : []; // Collect result in promise list
var promiseList = [];
_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;
}
var fieldNamePath = field.getNamePath(); // Add field validate rule in to promise list
if (!provideNameList || containsNamePath(namePathList, fieldNamePath)) {
var promise = field.validateRules(_objectSpread({
validateMessages: _objectSpread({}, defaultValidateMessages, {}, _this.validateMessages)
}, options)); // Wrap promise with field
promiseList.push(promise.then(function () {
return {
name: fieldNamePath,
errors: []
};
}).catch(function (errors) {
return Promise.reject({
name: fieldNamePath,
errors: errors
});
}));
}
});
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 (_ref4) {
var name = _ref4.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;
});
return returnPromise;
}; // ============================ Submit ============================
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;

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

@@ -0,0 +1,20 @@
import { InternalNamePath } from '../interface';
interface KV<T> {
key: InternalNamePath;
value: T;
}
/**
* NameMap like a `Map` but accepts `string[]` as key.
*/
declare class NameMap<T> {
private list;
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(): {
[name: string]: T;
};
}
export default NameMap;

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

@@ -0,0 +1,80 @@
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import { matchNamePath } from './valueUtil';
/**
* NameMap like a `Map` but accepts `string[]` as key.
*/
var NameMap = /*#__PURE__*/function () {
function NameMap() {
_classCallCheck(this, NameMap);
this.list = [];
}
_createClass(NameMap, [{
key: "set",
value: function set(key, value) {
var index = this.list.findIndex(function (item) {
return matchNamePath(item.key, key);
});
if (index !== -1) {
this.list[index].value = value;
} else {
this.list.push({
key: key,
value: value
});
}
}
}, {
key: "get",
value: function get(key) {
var result = this.list.find(function (item) {
return matchNamePath(item.key, key);
});
return result && result.value;
}
}, {
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.list = this.list.filter(function (item) {
return !matchNamePath(item.key, key);
});
}
}, {
key: "map",
value: function map(callback) {
return this.list.map(callback);
}
}, {
key: "toJSON",
value: function toJSON() {
var json = {};
this.map(function (_ref) {
var key = _ref.key,
value = _ref.value;
json[key.join('.')] = value;
return null;
});
return json;
}
}]);
return NameMap;
}();
export default NameMap;

View File

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

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

@@ -0,0 +1,31 @@
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
web/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
web/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}"
}
};

View File

@@ -0,0 +1 @@
export declare function toArray<T>(value?: T | T[] | null): T[];

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

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

View File

@@ -0,0 +1,6 @@
import { InternalNamePath, ValidateOptions, RuleObject, StoreValue } 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: ValidateOptions, validateFirst: boolean, messageVariables?: Record<string, string>): Promise<string[]>;

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

@@ -0,0 +1,286 @@
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _typeof from "@babel/runtime/helpers/esm/typeof";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import RawAsyncValidator from 'async-validator';
import * as React from 'react';
import warning from 'warning';
import { setValues } from './valueUtil';
import { defaultValidateMessages } from './messages'; // 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) {
var key = str.slice(2, -1);
return kv[key];
});
}
/**
* We use `async-validator` to validate rules. So have to hot replace the message with validator.
* { required: '${name} is required' } => { required: () => 'field is required' }
*/
function convertMessages(messages, name, rule, messageVariables) {
var kv = _objectSpread({}, rule, {
name: name,
enum: (rule.enum || []).join(', ')
});
var replaceFunc = function replaceFunc(template, additionalKV) {
return function () {
return replaceMessage(template, _objectSpread({}, kv, {}, additionalKV));
};
};
/* eslint-disable no-param-reassign */
function fillTemplate(source) {
var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Object.keys(source).forEach(function (ruleName) {
var value = source[ruleName];
if (typeof value === 'string') {
target[ruleName] = replaceFunc(value, messageVariables);
} else if (value && _typeof(value) === 'object') {
target[ruleName] = {};
fillTemplate(value, target[ruleName]);
} else {
target[ruleName] = value;
}
});
return target;
}
/* eslint-enable */
return fillTemplate(setValues({}, defaultValidateMessages, messages));
}
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 _callee(name, value, rule, options, messageVariables) {
var cloneRule, subRuleField, validator, messages, result, subResults;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
cloneRule = _objectSpread({}, rule); // 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 = convertMessages(options.validateMessages, name, cloneRule, messageVariables);
validator.messages(messages);
result = [];
_context.prev = 7;
_context.next = 10;
return Promise.resolve(validator.validate(_defineProperty({}, name, value), _objectSpread({}, options)));
case 10:
_context.next = 15;
break;
case 12:
_context.prev = 12;
_context.t0 = _context["catch"](7);
if (_context.t0.errors) {
result = _context.t0.errors.map(function (_ref2, index) {
var message = _ref2.message;
return (// Wrap ReactNode with `key`
React.isValidElement(message) ? React.cloneElement(message, {
key: "error_".concat(index)
}) : message
);
});
} else {
console.error(_context.t0);
result = [messages.default()];
}
case 15:
if (!(!result.length && subRuleField)) {
_context.next = 20;
break;
}
_context.next = 18;
return Promise.all(value.map(function (subValue, i) {
return validateRule("".concat(name, ".").concat(i), subValue, subRuleField, options, messageVariables);
}));
case 18:
subResults = _context.sent;
return _context.abrupt("return", subResults.reduce(function (prev, errors) {
return [].concat(_toConsumableArray(prev), _toConsumableArray(errors));
}, []));
case 20:
return _context.abrupt("return", result);
case 21:
case "end":
return _context.stop();
}
}
}, _callee, null, [[7, 12]]);
}));
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) {
var originValidatorFunc = currentRule.validator;
if (!originValidatorFunc) {
return currentRule;
}
return _objectSpread({}, currentRule, {
validator: function validator(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);
});
}
}
});
});
var rulePromises = filledRules.map(function (rule) {
return validateRule(name, value, rule, options, messageVariables);
});
var summaryPromise = (validateFirst ? finishOnFirstFailed(rulePromises) : finishOnAllFailed(rulePromises)).then(function (errors) {
if (!errors.length) {
return [];
}
return Promise.reject(errors);
}); // Internal catch error to avoid console error log.
summaryPromise.catch(function (e) {
return e;
});
return summaryPromise;
}
function finishOnAllFailed(_x6) {
return _finishOnAllFailed.apply(this, arguments);
}
function _finishOnAllFailed() {
_finishOnAllFailed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rulePromises) {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", Promise.all(rulePromises).then(function (errorsList) {
var _ref3;
var errors = (_ref3 = []).concat.apply(_ref3, _toConsumableArray(errorsList));
return errors;
}));
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _finishOnAllFailed.apply(this, arguments);
}
function finishOnFirstFailed(_x7) {
return _finishOnFirstFailed.apply(this, arguments);
}
function _finishOnFirstFailed() {
_finishOnFirstFailed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(rulePromises) {
var count;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
count = 0;
return _context3.abrupt("return", new Promise(function (resolve) {
rulePromises.forEach(function (promise) {
promise.then(function (errors) {
if (errors.length) {
resolve(errors);
}
count += 1;
if (count === rulePromises.length) {
resolve([]);
}
});
});
}));
case 2:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return _finishOnFirstFailed.apply(this, arguments);
}

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

@@ -0,0 +1,30 @@
import { InternalNamePath, NamePath, Store, StoreValue, EventArgs } from '../interface';
/**
* 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 getValue(store: Store, namePath: InternalNamePath): any;
export declare function setValue(store: Store, namePath: InternalNamePath, value: StoreValue): Store;
export declare function cloneByNamePathList(store: Store, namePathList: InternalNamePath[]): Store;
export declare function containsNamePath(namePathList: InternalNamePath[], namePath: InternalNamePath): boolean;
export declare function setValues<T>(store: T, ...restValues: T[]): T;
export declare function matchNamePath(namePath: InternalNamePath, changedNamePath: InternalNamePath | null): boolean;
declare type SimilarObject = string | number | {};
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[];
export {};

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

@@ -0,0 +1,157 @@
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _typeof from "@babel/runtime/helpers/esm/typeof";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import get from "rc-util/es/utils/get";
import set from "rc-util/es/utils/set";
import { toArray } from './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]
*/
export function getNamePath(path) {
return toArray(path);
}
export function getValue(store, namePath) {
var value = get(store, namePath);
return value;
}
export function setValue(store, namePath, value) {
var newStore = set(store, namePath, value);
return newStore;
}
export function cloneByNamePathList(store, namePathList) {
var newStore = {};
namePathList.forEach(function (namePath) {
var value = getValue(store, namePath);
newStore = setValue(newStore, namePath, value);
});
return newStore;
}
export function containsNamePath(namePathList, namePath) {
return namePathList && namePathList.some(function (path) {
return matchNamePath(path, namePath);
});
}
function isObject(obj) {
return _typeof(obj) === 'object' && obj !== null && Object.getPrototypeOf(obj) === Object.prototype;
}
/**
* Copy values into store and return a new values object
* ({ a: 1, b: { c: 2 } }, { a: 4, b: { d: 5 } }) => { a: 4, b: { c: 2, d: 5 } }
*/
function internalSetValues(store, values) {
var newStore = Array.isArray(store) ? _toConsumableArray(store) : _objectSpread({}, store);
if (!values) {
return newStore;
}
Object.keys(values).forEach(function (key) {
var prevValue = newStore[key];
var value = values[key]; // If both are object (but target is not array), we use recursion to set deep value
var recursive = isObject(prevValue) && isObject(value);
newStore[key] = recursive ? internalSetValues(prevValue, value || {}) : value;
});
return newStore;
}
export function setValues(store) {
for (var _len = arguments.length, restValues = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
restValues[_key - 1] = arguments[_key];
}
return restValues.reduce(function (current, newStore) {
return internalSetValues(current, newStore);
}, store);
}
export function matchNamePath(namePath, changedNamePath) {
if (!namePath || !changedNamePath || namePath.length !== changedNamePath.length) {
return false;
}
return namePath.every(function (nameUnit, i) {
return changedNamePath[i] === nameUnit;
});
}
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(_toConsumableArray(sourceKeys), _toConsumableArray(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 && 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;
}