function DefaultConnectedControl() { _classCallCheck(this, DefaultConnectedControl); return _possibleConstructorReturn(this, (DefaultConnectedControl.__proto__ || Object.getPrototypeOf(DefaultConnectedControl)). apply(this, arguments)); }
n/a
function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper)).call (this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; }
n/a
function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper)).call (this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; }
n/a
function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper)).call (this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; }
n/a
function Connect(props, context) { _classCallCheck(this, Connect); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.version = version; _this.store = props.store || context.store; (0, _invariant2["default"])(_this.store, 'Could not find "store" in either the context or ' + ('props of "' + connectDisplayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + connectDisplayName + '".')); var storeState = _this.store.getState(); _this.state = { storeState: storeState }; _this.clearCache(); return _this; }
n/a
function LocalForm(props) { _classCallCheck(this, LocalForm); var _this = _possibleConstructorReturn(this, (LocalForm.__proto__ || Object.getPrototypeOf(LocalForm)).call(this, props)); _this.store = props.store || (0, _redux.createStore)((0, _formsReducer2.default)(_defineProperty({}, props.model, props.initialState ))); _this.dispatch = function (action) { if (typeof action === 'function') { return action(_this.store.dispatch, _this.store.getState); } return _this.store.dispatch(action); }; return _this; }
n/a
function createBatchReducer(reducer, initialState) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var transformAction = options.transformAction; return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; var transformedAction = transformAction ? transformAction(action) : action; if (transformedAction.type === _actionTypes2.default.BATCH) { return transformedAction.actions.reduce(reducer, state); } return reducer(state, transformedAction); }; }
n/a
function combineForms(forms) { var model = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var mappedReducers = createForms(forms, model, options); return (0, _redux.combineReducers)(mappedReducers); }
n/a
function createFieldClass() { var customControlPropsMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultStrategy; // Use the fieldPropTypes if no controlProptypes have been defined to // maintain backwards compatibiltiy. var controlPropTypes = s.controlPropTypes || fieldPropTypes; function mapStateToProps(state, props) { var model = props.model; var modelString = (0, _getModel2.default)(model, state); var fieldValue = s.getFieldFromState(state, modelString) || _initialFieldState2.default; return { model: modelString, fieldValue: fieldValue }; } var options = { controlPropsMap: _extends({}, _controlPropsMap3.default, customControlPropsMap) }; // TODO: refactor var defaultControlPropsMap = { checkbox: { changeAction: s.actions.checkWithValue, getValue: _getValue.getCheckboxValue, isToggle: true }, radio: { isToggle: true } }; var Field = function (_Component) { _inherits(Field, _Component); function Field() { _classCallCheck(this, Field); return _possibleConstructorReturn(this, (Field.__proto__ || Object.getPrototypeOf(Field)).apply(this, arguments)); } _createClass(Field, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { var dynamic = this.props.dynamic; if (dynamic) { return (0, _deepCompareChildren2.default)(this, nextProps); } return (0, _shallowCompareWithoutChildren2.default)(this, nextProps); } }, { key: 'createControlComponent', value: function createControlComponent(control) { var props = this.props; if (!control || !control.props || control instanceof _controlComponent2.default) { return control; } var controlType = getControlType(control, props, options); var _props$mapProps = props.mapProps, mapProps = _props$mapProps === undefined ? options.controlPropsMap[controlType] : _props$mapProps; var controlProps = (0, _pick2.default)(props, Object.keys(controlPropTypes)); if (!mapProps) { return _react2.default.cloneElement(control, null, this.mapChildrenToControl(control.props.children)); } return _react2.default.createElement(s.Control, _extends({}, controlProps, { control: control, controlProps: control.props, component: control.type, mapProps: mapProps }, defaultControlPropsMap[controlType] || {})); } }, { key: 'mapChildrenToControl', value: function mapChildrenToControl(children) { var _this2 = this; if (_react2.default.Children.count(children) > 1) { return _react2.default.Children.map(children, function (child) { return _this2.createControlComponent(child); }); } return this.createControlComponent(children); } }, { key: 'render', value: function render() { var _props = this.props, component = _props.component, children = _props.children, fieldValue = _props.fieldValue; var allowedProps = (0, _omit2.default)(this.props, Object.keys(controlPropTypes)); var renderableChildren = typeof children === 'function' ? children(fieldValue) : children; if (!component) { (0, _invariant2.default)(_react2.default.Children.count(renderableChildren) === 1, 'Empty wrapper components for <Field > are only possible' + 'when there is a single child. Please check the children' + ('passed into <Field model="' + this.props.model + '">.')); return this.createControlComponent(renderableChildren); } return _react2.default.createElement(component, allowedProps, this.mapChildrenToControl(renderableChildren)); } }]); return Field; }(_react.Component); if (process.env.NODE_ENV !== 'production') ...
n/a
function createForms(forms) { var model = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var formKeys = Object.keys(forms); var modelReducers = {}; var initialFormState = {}; var optionsWithDefaults = _extends({}, defaults, options); var key = optionsWithDefaults.key, plugins = optionsWithDefaults.plugins, formOptions = _objectWithoutProperties(optionsWithDefaults, ['key', 'plugins']); var cacheId = cacheModelState({}); formKeys.forEach(function (formKey) { var formValue = forms[formKey]; var subModel = getSubModelString(model, formKey); if (typeof formValue === 'function') { var initialState = void 0; try { initialState = formValue(undefined, _nullAction2.default); } catch (error) { initialState = null; } modelReducers[formKey] = cacheReducer(strategy.modeled(formValue, subModel), subModel, cacheId); initialFormState[formKey] = initialState; } else { modelReducers[formKey] = cacheReducer(strategy.modelReducer(subModel, formValue), subModel, cacheId); initialFormState[formKey] = strategy.toJS(formValue); } }); return _extends({}, modelReducers, _defineProperty({}, key, function (state, action) { return strategy.formReducer(model, initialFormState, _extends({ plugins: plugins }, formOptions))(state, _extends({}, action, { state: Object.assign({}, modelCache[cacheId]) })); })); }
...
// set initial state with Immutable Map
const initialUserState = Immutable.fromJS({
firstName: '',
lastName: '',
});
const store = applyMiddleware(thunk)(createStore)(combineReducers({
...createForms({
user: initialUserState,
})
}));
export default store;
...
function formSelector(formState) { return _extends({}, formState, { get valid() { return (0, _isValid2.default)(formState); }, get pending() { return (0, _isPending2.default)(formState); }, get touched() { return (0, _isTouched2.default)(formState); }, get retouched() { return (0, _isRetouched2.default)(formState); } }); }
n/a
function createFormReducer(model) { var initialState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _options$plugins = options.plugins, plugins = _options$plugins === undefined ? [] : _options$plugins, customInitialFieldState = options.initialFieldState, _options$transformAct = options.transformAction, transformAction = _options$transformAct === undefined ? null : _options$transformAct; var modelPath = (0, _toPath2.default)(model); var initialFormState = createInitialState(model, initialState, customInitialFieldState, options); var defaultPlugins = [(0, _formActionsReducer.createFormActionsReducer)({ initialFieldState: customInitialFieldState }), _changeActionReducer2 .default]; var wrappedPlugins = plugins.concat(defaultPlugins).map(function (plugin) { return wrapFormReducer(plugin, modelPath, initialFormState); }); return (0, _batchedEnhancer2.default)(_composeReducers2.default.apply(undefined, _toConsumableArray(wrappedPlugins)), undefined , { transformAction: transformAction }); }
n/a
function getFieldFromState(state, modelString) { var s = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultStrategy; var form = state && '$form' in state ? state : s.getForm(state, modelString); if (!form || !form.$form) return null; if (!modelString.length) return form; (0, _invariant2.default)(form, 'Could not find form for "%s" in the store.', modelString); var formPath = (0, _toPath2.default)(form.$form.model); var fieldPath = (0, _toPath2.default)(modelString).slice(formPath.length); var field = (0, _get2.default)(form, fieldPath); if (!field) return null; if ((0, _isPlainObject2.default)(field) && '$form' in field) return field.$form; return field; }
n/a
function get(object, path, defaultValue) { var modelString = path; if (typeof path === 'number') { var result = object[path]; return result === undefined ? defaultValue : result; } if (!path.length) return object; if ((0, _endsWith2.default)(modelString, '.')) { modelString = modelString.slice(0, -1); } else if ((0, _endsWith2.default)(modelString, '[]')) { modelString = modelString.slice(0, -2); } return (0, _lodash2.default)(object, modelString, defaultValue); }
n/a
function _createModelReducer(model) { var initialState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : object; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var modelPath = (0, _toPath2.default)(model); var modelReducer = function modelReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; if (!action.model) { return state; } var path = (0, _toPath2.default)(action.model); if (!(0, _arraysEqual2.default)(path.slice(0, modelPath.length), modelPath)) { return state; } var localPath = path.slice(modelPath.length); switch (action.type) { case _actionTypes2.default.CHANGE: case _actionTypes2.default.LOAD: if (!localPath.length) { return action.value; } if (getter(state, localPath) === action.value) { return state; } return setter(state, localPath, action.value); case _actionTypes2.default.RESET: if (!localPath.length) { return initialState; } if (getter(state, localPath) === getter(initialState, localPath)) { return state; } return setter(state, localPath, getter(initialState, localPath)); default: return state; } }; return (0, _batchedEnhancer2.default)(modelReducer, initialState, options); }
n/a
function modelReducerEnhancer(reducer, model) { var initialState = void 0; try { initialState = reducer(undefined, _nullAction2.default); } catch (error) { initialState = null; } var _modelReducer = modelReducerCreator(model, initialState, options); return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; var updatedState = _modelReducer(state, action); return reducer(updatedState, action); }; }
n/a
function track(model) { for (var _len = arguments.length, predicates = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { predicates[_key - 1] = arguments[_key]; } var isPartial = model[0] === '.'; return function (fullState, parentModel) { var childModel = isPartial ? model.slice(1) : model; var state = isPartial ? s.get(fullState, parentModel) : fullState; var _childModel$split = childModel.split(/\[\]\.?/), _childModel$split2 = _toArray(_childModel$split), parentModelPath = _childModel$split2[0], childModelPaths = _childModel$split2.slice(1); var fullPath = parentModelPath; var subState = s.get(state, fullPath); predicates.forEach(function (predicate, i) { var childModelPath = childModelPaths[i]; var predicateIteratee = (0, _iteratee2.default)(predicate); var subPath = childModelPath ? (0, _findKey2.default)(subState, predicateIteratee) + '.' + childModelPath : '' + (0, _findKey2 .default)(subState, predicateIteratee); subState = s.get(subState, subPath); fullPath += '.' + subPath; }); if ((0, _isMulti2.default)(childModel) && predicates.length < childModelPaths.length) { fullPath += '[]'; } return isPartial ? parentModel + '.' + fullPath : fullPath; }; }
n/a
function DefaultConnectedControl() { _classCallCheck(this, DefaultConnectedControl); return _possibleConstructorReturn(this, (DefaultConnectedControl.__proto__ || Object.getPrototypeOf(DefaultConnectedControl)). apply(this, arguments)); }
n/a
function DefaultConnectedControlButton() { _classCallCheck(this, DefaultConnectedControlButton); return _possibleConstructorReturn(this, (DefaultConnectedControlButton.__proto__ || Object.getPrototypeOf(DefaultConnectedControlButton )).apply(this, arguments)); }
n/a
function DefaultConnectedControlCheckbox() { _classCallCheck(this, DefaultConnectedControlCheckbox); return _possibleConstructorReturn(this, (DefaultConnectedControlCheckbox.__proto__ || Object.getPrototypeOf(DefaultConnectedControlCheckbox )).apply(this, arguments)); }
n/a
function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper)).call (this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; }
n/a
function DefaultConnectedControlFile() { _classCallCheck(this, DefaultConnectedControlFile); return _possibleConstructorReturn(this, (DefaultConnectedControlFile.__proto__ || Object.getPrototypeOf(DefaultConnectedControlFile )).apply(this, arguments)); }
n/a
function DefaultConnectedControlInput() { _classCallCheck(this, DefaultConnectedControlInput); return _possibleConstructorReturn(this, (DefaultConnectedControlInput.__proto__ || Object.getPrototypeOf(DefaultConnectedControlInput )).apply(this, arguments)); }
n/a
function DefaultConnectedControlRadio() { _classCallCheck(this, DefaultConnectedControlRadio); return _possibleConstructorReturn(this, (DefaultConnectedControlRadio.__proto__ || Object.getPrototypeOf(DefaultConnectedControlRadio )).apply(this, arguments)); }
n/a
function DefaultConnectedControlReset() { _classCallCheck(this, DefaultConnectedControlReset); return _possibleConstructorReturn(this, (DefaultConnectedControlReset.__proto__ || Object.getPrototypeOf(DefaultConnectedControlReset )).apply(this, arguments)); }
...
*/
setSubmitFailed: (model: string) => FieldAction;
/**
* Returns an action that, when handled by a formReducer, changes the state of the field model in the form to its initial state.
*
* Tips:
* * This action will reset the field state, but will not reset the model value in the model reducer. To reset both the field and
model, use actions.reset(model).
*/
setInitial: (model: string) => FieldAction;
/**
* Waits for a submission promise to be completed, then, if successful:
* * Sets .submitted property of form for model to true
* * Sets .validity property of form for model to the response (or true if the response is undefined).
...
function DefaultConnectedControlSelect() { _classCallCheck(this, DefaultConnectedControlSelect); return _possibleConstructorReturn(this, (DefaultConnectedControlSelect.__proto__ || Object.getPrototypeOf(DefaultConnectedControlSelect )).apply(this, arguments)); }
n/a
function DefaultConnectedControlText() { _classCallCheck(this, DefaultConnectedControlText); return _possibleConstructorReturn(this, (DefaultConnectedControlText.__proto__ || Object.getPrototypeOf(DefaultConnectedControlText )).apply(this, arguments)); }
n/a
function DefaultConnectedControlTextArea() { _classCallCheck(this, DefaultConnectedControlTextArea); return _possibleConstructorReturn(this, (DefaultConnectedControlTextArea.__proto__ || Object.getPrototypeOf(DefaultConnectedControlTextArea )).apply(this, arguments)); }
n/a
function Connect(props, context) { _classCallCheck(this, Connect); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.version = version; _this.store = props.store || context.store; (0, _invariant2["default"])(_this.store, 'Could not find "store" in either the context or ' + ('props of "' + connectDisplayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + connectDisplayName + '".')); var storeState = _this.store.getState(); _this.state = { storeState: storeState }; _this.clearCache(); return _this; }
n/a
function Form(props) { _classCallCheck(this, Form); var _this = _possibleConstructorReturn(this, (Form.__proto__ || Object.getPrototypeOf(Form)).call(this, props)); _this.handleSubmit = _this.handleSubmit.bind(_this); _this.handleReset = _this.handleReset.bind(_this); _this.handleValidSubmit = _this.handleValidSubmit.bind(_this); _this.handleInvalidSubmit = _this.handleInvalidSubmit.bind(_this); _this.attachNode = _this.attachNode.bind(_this); _this.state = { lastSubmitEvent: null }; return _this; }
n/a
store = function () { [native code] }
n/a
store = function () { [native code] }
n/a
function clearCache() { this.dispatchProps = null; this.stateProps = null; this.mergedProps = null; this.haveOwnPropsChanged = true; this.hasStoreStateChanged = true; this.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; this.renderedElement = null; this.finalMapDispatchToProps = null; this.finalMapStateToProps = null; }
n/a
function componentDidMount() { this.trySubscribe(); }
n/a
function componentWillReceiveProps(nextProps) { if (!pure || !(0, _shallowEqual2["default"])(nextProps, this.props)) { this.haveOwnPropsChanged = true; } }
n/a
function componentWillUnmount() { this.tryUnsubscribe(); this.clearCache(); }
n/a
function componentWillUpdate() { if (this.version === version) { return; } // We are hot reloading! this.version = version; this.trySubscribe(); this.clearCache(); }
n/a
function computeDispatchProps(store, props) { if (!this.finalMapDispatchToProps) { return this.configureFinalMapDispatch(store, props); } var dispatch = store.dispatch; var dispatchProps = this.doDispatchPropsDependOnOwnProps ? this.finalMapDispatchToProps(dispatch, props) : this.finalMapDispatchToProps (dispatch); if (process.env.NODE_ENV !== 'production') { checkStateShape(dispatchProps, 'mapDispatchToProps'); } return dispatchProps; }
n/a
function computeStateProps(store, props) { if (!this.finalMapStateToProps) { return this.configureFinalMapState(store, props); } var state = store.getState(); var stateProps = this.doStatePropsDependOnOwnProps ? this.finalMapStateToProps(state, props) : this.finalMapStateToProps(state ); if (process.env.NODE_ENV !== 'production') { checkStateShape(stateProps, 'mapStateToProps'); } return stateProps; }
n/a
function configureFinalMapDispatch(store, props) { var mappedDispatch = mapDispatch(store.dispatch, props); var isFactory = typeof mappedDispatch === 'function'; this.finalMapDispatchToProps = isFactory ? mappedDispatch : mapDispatch; this.doDispatchPropsDependOnOwnProps = this.finalMapDispatchToProps.length !== 1; if (isFactory) { return this.computeDispatchProps(store, props); } if (process.env.NODE_ENV !== 'production') { checkStateShape(mappedDispatch, 'mapDispatchToProps'); } return mappedDispatch; }
n/a
function configureFinalMapState(store, props) { var mappedState = mapState(store.getState(), props); var isFactory = typeof mappedState === 'function'; this.finalMapStateToProps = isFactory ? mappedState : mapState; this.doStatePropsDependOnOwnProps = this.finalMapStateToProps.length !== 1; if (isFactory) { return this.computeStateProps(store, props); } if (process.env.NODE_ENV !== 'production') { checkStateShape(mappedState, 'mapStateToProps'); } return mappedState; }
n/a
function getWrappedInstance() { (0, _invariant2["default"])(withRef, 'To access the wrapped instance, you need to specify ' + '{ withRef: true } as the fourth argument of the connect() call.'); return this.refs.wrappedInstance; }
n/a
function handleChange() { if (!this.unsubscribe) { return; } var storeState = this.store.getState(); var prevStoreState = this.state.storeState; if (pure && prevStoreState === storeState) { return; } if (pure && !this.doStatePropsDependOnOwnProps) { var haveStatePropsChanged = tryCatch(this.updateStatePropsIfNeeded, this); if (!haveStatePropsChanged) { return; } if (haveStatePropsChanged === errorObject) { this.statePropsPrecalculationError = errorObject.value; } this.haveStatePropsBeenPrecalculated = true; } this.hasStoreStateChanged = true; this.setState({ storeState: storeState }); }
...
handleChange(values) { ... }
handleUpdate(form) { ... }
handleSubmit(values) { ... }
render() {
return (
<LocalForm
onUpdate={(form) => this.handleUpdate(form)}
onChange={(values) => this.handleChange(values)}
onSubmit={(values) => this.handleSubmit(values)}
>
<Control.text model=".username" />
<Control.text model=".password" />
</LocalForm>
);
}
...
function isSubscribed() { return typeof this.unsubscribe === 'function'; }
n/a
function render() { var haveOwnPropsChanged = this.haveOwnPropsChanged, hasStoreStateChanged = this.hasStoreStateChanged, haveStatePropsBeenPrecalculated = this.haveStatePropsBeenPrecalculated, statePropsPrecalculationError = this.statePropsPrecalculationError, renderedElement = this.renderedElement; this.haveOwnPropsChanged = false; this.hasStoreStateChanged = false; this.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; if (statePropsPrecalculationError) { throw statePropsPrecalculationError; } var shouldUpdateStateProps = true; var shouldUpdateDispatchProps = true; if (pure && renderedElement) { shouldUpdateStateProps = hasStoreStateChanged || haveOwnPropsChanged && this.doStatePropsDependOnOwnProps; shouldUpdateDispatchProps = haveOwnPropsChanged && this.doDispatchPropsDependOnOwnProps; } var haveStatePropsChanged = false; var haveDispatchPropsChanged = false; if (haveStatePropsBeenPrecalculated) { haveStatePropsChanged = true; } else if (shouldUpdateStateProps) { haveStatePropsChanged = this.updateStatePropsIfNeeded(); } if (shouldUpdateDispatchProps) { haveDispatchPropsChanged = this.updateDispatchPropsIfNeeded(); } var haveMergedPropsChanged = true; if (haveStatePropsChanged || haveDispatchPropsChanged || haveOwnPropsChanged) { haveMergedPropsChanged = this.updateMergedPropsIfNeeded(); } else { haveMergedPropsChanged = false; } if (!haveMergedPropsChanged && renderedElement) { return renderedElement; } if (withRef) { this.renderedElement = (0, _react.createElement)(WrappedComponent, _extends({}, this.mergedProps, { ref: 'wrappedInstance' })); } else { this.renderedElement = (0, _react.createElement)(WrappedComponent, this.mergedProps); } return this.renderedElement; }
...
const store = testCreateStore({
test: modelReducer('test', initialState),
testForm: formReducer('test', initialState),
});
const container = document.createElement('div');
const field = ReactDOM.render(
<Provider store={store}>
<Control.input model="test.foo" />
</Provider>,
container);
const input = TestUtils.findRenderedDOMComponentWithTag(field, 'input');
...
function shouldComponentUpdate() { return !pure || this.haveOwnPropsChanged || this.hasStoreStateChanged; }
n/a
function trySubscribe() { if (shouldSubscribe && !this.unsubscribe) { this.unsubscribe = this.store.subscribe(this.handleChange.bind(this)); this.handleChange(); } }
n/a
function tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; } }
n/a
function updateDispatchPropsIfNeeded() { var nextDispatchProps = this.computeDispatchProps(this.store, this.props); if (this.dispatchProps && (0, _shallowEqual2["default"])(nextDispatchProps, this.dispatchProps)) { return false; } this.dispatchProps = nextDispatchProps; return true; }
n/a
function updateMergedPropsIfNeeded() { var nextMergedProps = computeMergedProps(this.stateProps, this.dispatchProps, this.props); if (this.mergedProps && checkMergedEquals && (0, _shallowEqual2["default"])(nextMergedProps, this.mergedProps)) { return false; } this.mergedProps = nextMergedProps; return true; }
n/a
function updateStatePropsIfNeeded() { var nextStateProps = this.computeStateProps(this.store, this.props); if (this.stateProps && (0, _shallowEqual2["default"])(nextStateProps, this.stateProps)) { return false; } this.stateProps = nextStateProps; return true; }
...
);
const filter = ({ constructor }) =>
constructor.displayName === 'Connect(Control)';
const components = TestUtils.findAllInRenderedTree(field, filter);
assert.lengthOf(components, 1, 'exactly one connected Control was rendered');
const [component] = components;
const oldStateProps = component.stateProps;
const didUpdate = component.updateStatePropsIfNeeded();
const failures = Object.keys(component.stateProps).filter((k) =>
component.stateProps[k] !== oldStateProps[k]);
assert(
!didUpdate,
`stateProps should not have changed, changed props: ${failures.join(', ')}`);
});
...
addIntent = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
}
if (validityChanged) {
dispatch(s.actions.setFieldsErrors(model, fieldsErrors, { merge: true }));
}
if (submit) {
dispatch(s.actions.addIntent(model, { type: 'submit' }));
}
}
}, {
key: 'handleValidSubmit',
value: function handleValidSubmit(options) {
var _props2 = this.props,
dispatch = _props2.dispatch,
...
asyncSetErrors = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
n/a
asyncSetValidity = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
});
const validator = (value, done) => done({
good: value > 4,
bad: value > 5,
});
actions.asyncSetValidity('test.foo', validator)(dispatch, getState);
});
it('should work with forms to asynchronously call setValidity() action', testDone => {
const reducer = formReducer('test');
const dispatch = action => {
if (action.type === actionTypes.SET_VALIDITY) {
const actual = reducer(undefined, action);
...
batch = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
import thunk from 'redux-thunk';
import { modelReducer, formReducer, actions, actionTypes } from '../src';
describe('batched actions', () => {
it('should batch actions', (done) => {
const mockStore = configureMockStore([thunk]);
const action = actions.batch('test.foo', [
actions.change('test.foo', 'testing'),
actions.focus('test.foo'),
actions.toggle('test.foo'),
]);
const expectedActions = [
{
...
blur = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
type: actionTypes.FOCUS,
model: 'foo.bar',
value: undefined,
});
});
});
describe('actions.blur()', () => {
it('should return an action', () => {
assert.deepEqual(
actions.blur('foo.bar'),
{
type: actionTypes.BLUR,
model: 'foo.bar',
});
...
change = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
* @returns {typeof value} The parsed/processed value
*/
parser?: (value: any, previous?: any) => any;
/**
* An action creator (function) that specifies which action the <Field> component should use when dispatching a change
to the model.
*
* By default, this action is:
* * actions.change(model, value) for text input controls
* * actions.toggle(model, value) for checkboxes (single-value models)
* * actions.xor(model, value) for checkboxes (multi-value models)
*
* Notes:
* * Use changeAction to do any other custom actions whenever your value is to change.
* * Since changeAction expects an action creator and redux-thunk is used, you can asynchronously dispatch actions by returning
a thunk.
*
...
check = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
n/a
checkWithValue = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
n/a
clearIntents = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
if (_isNative2.default) return;
var focused = fieldValue.focus;
if (focused && _this2.node.focus && (!_this2.props.isToggle || typeof intent.value === 'undefined
x27; || intent.value === controlProps.value)) {
_this2.node.focus();
dispatch(_actions2.default.clearIntents(model, intent));
}
return;
}
case 'validate':
if ((0, _containsEvent2.default)(validateOn, 'change')) {
_this2.validate({ clearIntents: intent });
...
filter = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
},
});
fn(dispatch, getState);
});
});
describe('actions.filter() thunk', () => {
it('should return a function that dispatches a change event', done => {
const fn = actions.filter('foo.bar', i => i % 2 === 0);
const dispatch = action => {
done(assert.equal(
action.type,
actionTypes.CHANGE));
};
...
focus = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
assert.throws(() => fn(dispatch, getState), 'Error moving array item: invalid bounds 3, 4');
});
});
});
describe('field action creators', () => {
describe('actions.focus()', () => {
it('should return an action', () => {
assert.deepEqual(
actions.focus('foo.bar'),
{
type: actionTypes.FOCUS,
model: 'foo.bar',
value: undefined,
...
load = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
<Control.text
model="test.foo"
/>
</Provider>
);
it('should reset the control to the last loaded value', () => {
store.dispatch(actions.load('test.foo', 'new foo'));
store.dispatch(actions.reset('test.foo'));
assert.equal(get(store.getState().test, 'foo'), 'new foo');
});
});
describe('deep initial value after reset', () => {
...
map = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
return _extends({}, action, {
value: action.value.toJS()
});
}
if (action.actions) {
return _extends({}, action, {
actions: action.actions.map(transformAction)
});
}
return action;
}
function immutableFormReducer(model) {
...
merge = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
* To reset just the field state (in the form reducer), use actions.setInitial(model).
*/
reset: (model: string) => ModelAction;
/**
* Dispatches an actions.change(...) action that merges the values into the value specified by the model.
*
* Use this action to update multiple and/or deep properties into a model, if the model represents an object.
* This uses icepick.merge(modelValue, values) internally.
*/
merge: (model: string, values: any) => ActionThunk;
/**
* Dispatches an actions.change(...) action that applies an "xor" operation to the array represented by the model; that
is, it "toggles" an item in an array.
* If the model value contains item, it will be removed. If the model value doesn't contain item, it will be added.
*
* This action is most useful for toggling a checkboxes whose values represent items in a model's array.
...
move = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
actions.remove('foo.bar', 2)(nextDispatch, getNextState);
};
actions.remove('foo.bar', 2)(dispatch, getState);
});
});
describe('actions.move() thunk', () => {
it('should return a function that dispatches a change event', done => {
const fn = actions.move('foo.bar', 2, 0);
const dispatch = action => {
done(assert.equal(
action.type,
actionTypes.CHANGE));
};
...
omit = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
mapProps={{
onResponderGrant: ({ onFocus }) => onFocus,
onRegionChange: ({ onChange }) => onChange,
onRegionChangeComplete: ({ onBlur }) => onBlur,
region: ({ modelValue }) => modelValue,
...props.mapProps,
}}
{...omit(props, 'mapProps')}
/>
);
Control.Picker = (props) => (
<Control
component={Picker}
mapProps={{
...
push = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
* This action is most useful for toggling a checkboxes whose values represent items in a model's array.
* @param item the item to be "toggled" in the model value.
*/
xor: (model: string, item: any) => ActionThunk;
/**
* Dispatches an actions.change(...) action that "pushes" the item to the array represented by the model.
*
* This action does not mutate the model. It only simulates the mutable .push() method
.
*/
push: (model: string, item: any) => ActionThunk;
/**
* Dispatches an actions.change(...) action that sets the model to true if it is falsey, and false if it is truthy.
*
* This action is most useful for single checkboxes.
*/
...
remove = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
const baseStrategy = {
get: immutableGetFromState,
set: immutableSet,
getValue,
keys: immutableKeys,
splice: (list, ...args) => list.splice(...args),
merge: (map, ...args) => map.merge(...args),
remove: (map, ...args) => map.remove(...args),
push: (list, ...args) => list.push(...args),
length: (list) => list.size,
object: new Immutable.Map(),
array: new Immutable.List(),
isObject: (state) => (isPlainObject(state) || Immutable.Map.isMap(state)),
};
...
reset = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
*/
setSubmitFailed: (model: string) => FieldAction;
/**
* Returns an action that, when handled by a formReducer, changes the state of the field model in the form to its initial state.
*
* Tips:
* * This action will reset the field state, but will not reset the model value in the model reducer. To reset both the field and
model, use actions.reset(model).
*/
setInitial: (model: string) => FieldAction;
/**
* Waits for a submission promise to be completed, then, if successful:
* * Sets .submitted property of form for model to true
* * Sets .validity property of form for model to the response (or true if the response is undefined).
...
resetErrors = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
it('should be aliased to resetErrors()', () => {
const stateWithErrors = reducer(
undefined,
actions.setErrors('test.foo', { bar: true, baz: true }));
const actualState = reducer(
stateWithErrors,
actions.resetErrors('test.foo'));
assert.deepEqual(actualState.foo.validity, {});
assert.deepEqual(actualState.foo.errors, {});
assert.isTrue(isValid(actualState.foo));
});
});
...
resetValidity = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
errors: { bar: true, baz: true },
});
assert.isFalse(isValid(stateWithErrors.foo));
const actualState = reducer(
stateWithErrors,
actions.resetValidity('test.foo'));
assert.containSubset(
actualState.foo,
{
validity: {},
errors: {},
});
...
setDirty = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
{
type: actionTypes.SET_PRISTINE,
model: 'foo.bar',
});
});
});
describe('actions.setDirty()', () => {
it('should return an action', () => {
assert.deepEqual(
actions.setDirty('foo.bar'),
{
type: actionTypes.SET_DIRTY,
model: 'foo.bar',
});
...
setErrors = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
* @default false
*/
silent?: boolean;
}
interface ValidityOptions {
/**
* If true, the validity will be set for .errors instead of .validity on the field. This is equivalent to actions.setErrors().
*/
errors?: boolean;
}
interface SetErrorsOptions {
async?: boolean;
}
...
setFieldsErrors = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
// Compute form-level validity
if (!fieldsErrors.hasOwnProperty('') && !~fieldKeys.indexOf('')) {
fieldsErrors[''] = false;
validityChanged = validityChanged || (0, _isValidityInvalid2.default)(formValue.$form.errors);
}
if (validityChanged) {
dispatch(s.actions.setFieldsErrors(model, fieldsErrors, { merge: true }));
}
if (submit) {
dispatch(s.actions.addIntent(model, { type: 'submit' }));
}
}
}, {
...
setFieldsValidity = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
it('should have correct overall validity after a field validity is reset', () => {
const reducer = formReducer('test', {
foo: 'one',
bar: 'two',
});
const bothInvalidState = reducer(undefined, actions.setFieldsValidity('test'
;, {
foo: false,
bar: false,
}));
assert.isFalse(isValid(bothInvalidState));
const oneInvalidState = reducer(bothInvalidState, actions.setValidity('test.foo', true));
...
setInitial = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
*/
load: (model: string, value: any) => ModelAction;
/**
* Returns an action that, when handled by a modelReducer, changes the value of the respective model to its initial value.
*
* This action will reset both the model value in the model reducer, and the model field state in the form reducer (if it exists
).
* To reset just the field state (in the form reducer), use actions.setInitial(model).
*/
reset: (model: string) => ModelAction;
/**
* Dispatches an actions.change(...) action that merges the values into the value specified by the model.
*
* Use this action to update multiple and/or deep properties into a model, if the model represents an object.
* This uses icepick.merge(modelValue, values) internally.
...
setPending = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
describe('setPending()', () => {
it('should set the pending state of the field to true ' +
'and the submitted state to false', () => {
const reducer = formReducer('test');
assert.containSubset(
reducer(undefined, actions.setPending('test.foo'))
.foo,
{
pending: true,
submitted: false,
});
});
...
setPristine = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
{
type: actionTypes.BLUR,
model: 'foo.bar',
});
});
});
describe('actions.setPristine()', () => {
it('should return an action', () => {
assert.deepEqual(
actions.setPristine('foo.bar'),
{
type: actionTypes.SET_PRISTINE,
model: 'foo.bar',
});
...
setSubmitFailed = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
**Batch Action Enhancements**
- Batching a single action now dispatches that action, instead of unnecessarily wrapping it in a `batch()` action.
**Field Action Enhancements**
- 🆕 `actions.setValidating(model[, validating])` will change the field's `.validating` state to `validating` (or `true` if
not provided).
- This is useful for distinguishing between `.pending` (a form/subForm is being submitted) and `.validating` (a field is asynchronously
being validated).
- 🆕 Of course, there is a new `actionTypes.SET_VALIDATING` action type.
- `actions.setSubmitFailed(model[, submitFailed])` now takes in a `submitFailed` parameter
(defaults to `true`).
...
setSubmitted = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
const getInitialState = testContext.getInitialState;
describe('field actions', () => {
describe('change()', () => {
it('should set the retouched property to true upon change after submit', () => {
const initialState = getInitialState({ foo: '' });
const reducer = formReducer('test', initialState);
const state = reducer(undefined, actions.setSubmitted('test'));
assert.containSubset(
state.$form,
{
submitted: true,
retouched: false,
}, 'not retouched yet');
...
setTouched = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
it('should still have the initial state', () => {
assert.deepEqual(
lazyReducer(undefined, { type: 'ANY' }).forms.$form.initialValue,
initialState);
});
it('should create the fields only when interacted with', () => {
const action = actions.setTouched('foo');
const touchedState = lazyReducer(undefined, action);
assert.property(touchedState.forms, 'foo');
assert.isTrue(touchedState.forms.foo.touched);
});
});
...
setUntouched = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
});
describe('setUntouched()', () => {
it('should set the touched state to false', () => {
const reducer = formReducer('test');
assert.containSubset(
reducer(undefined, actions.setUntouched('test.foo'))
.foo,
{
touched: false,
});
});
});
...
setValidating = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
- If accessing an object or an array (i.e., a _subForm_), the form state is in `model.path.$form`.
- If accessing a plain field (e.g., a string, boolean, number, etc.), the field state is in `model.path`.
**Batch Action Enhancements**
- Batching a single action now dispatches that action, instead of unnecessarily wrapping it in a `batch()` action.
**Field Action Enhancements**
- 🆕 `actions.setValidating(model[, validating])` will change the field's `.validating
` state to `validating` (or `true` if not provided).
- This is useful for distinguishing between `.pending` (a form/subForm is being submitted) and `.validating` (a field is asynchronously
being validated).
- 🆕 Of course, there is a new `actionTypes.SET_VALIDATING` action type.
- `actions.setSubmitFailed(model[, submitFailed])` now takes in a `submitFailed` parameter (defaults to `true`).
...
setValidity = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
*
* @param model The model whose validity will be set.
* @param validity Boolean value or an object indicating which validation keys of the field model are valid.
*/
setValidity: (model: string, validity: boolean | string | ValidityObject | ErrorsObject, options?: ValidityOptions) => FieldAction
;
/**
* Returns an action thunk that calculates the validity of the model based on the function/object validators. Then, the thunk dispatches
actions.setValidity(model, validity).
*
* A validator is a function that returns true if valid, and false if invalid.
* @param model The model whose validity will be calculated.
* @param validators A validator function or an object whose keys are validation keys (such as 'required') and values
are validators.
*/
validate: (model: string, validators: Function | Validators) => ActionThunk;
...
silentFocus = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
n/a
submit = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
/**
* Returns an action thunk that calculates the validity of the model based on the async function asyncValidator.
* That function dispatches actions.setValidity(model, validity) by calling done(validity).
*
* Tips:
* * This action is useful for general-purpose asynchronous validation using callbacks. If you are using promises, using actions
.submit(model, promise) is a cleaner pattern.
*
* @param model The model whose validity will be set
* @param asyncValidator A function that is given two arguments: value - the value of the model, done - the callback where the calculated
validity is passed in as the argument.
*/
asyncSetValidity: (model: string, asyncValidator: AsyncValidatorFn) => ActionThunk;
/**
...
submitFields = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
n/a
toggle = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
*/
parser?: (value: any, previous?: any) => any;
/**
* An action creator (function) that specifies which action the <Field> component should use when dispatching a change
to the model.
*
* By default, this action is:
* * actions.change(model, value) for text input controls
* * actions.toggle(model, value) for checkboxes (single-value models)
* * actions.xor(model, value) for checkboxes (multi-value models)
*
* Notes:
* * Use changeAction to do any other custom actions whenever your value is to change.
* * Since changeAction expects an action creator and redux-thunk is used, you can asynchronously dispatch actions by returning
a thunk.
*
* @param model The model that is being changed
...
validSubmit = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
const store = mockStore(
() => ({
testForm: reducer(undefined, actions.setValidity('test', false)),
}),
expectedActions,
done);
const action = actions.validSubmit('test', new Promise((r) => r()));
store.dispatch(action);
});
it('should be able to resolve a form as valid', (done) => {
const store = createTestStore(testCreateStore({
testForm: formReducer('test'),
...
validate = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
/**
* Returns an action thunk that calculates the errors of the model based on the function/object errorValidators. Then, the thunk
dispatches actions.setErrors(model, errors).
*
* An error validator is a function that returns true or a truthy value (such as a string) if invalid, and false if valid.
*
* Tips:
* * As previously stated, if you aren't using error messages, use actions.validate(model, validators) as a cleaner pattern.
* @param model
* @param errorValidators An error validator or an object whose keys are error keys (such as 'incorrect') and values are
error validators.
*/
validateErrors: (model: string, errorValidators: ValidatorFn | Validators) => ActionThunk;
/**
* Can be dispatched to reset the validity and errors of any model at any time.
...
validateErrors = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
[
{ model: 'test.foo', type: actionTypes.SET_ERRORS, errors: 'Value is invalid' },
{ model: 'test.foo', type: actionTypes.SET_ERRORS, errors: 'Value is invalid again' },
{ model: 'test.foo', type: actionTypes.SET_ERRORS, errors: false },
],
done);
store.dispatch(actions.validateErrors('test.foo',
(val) => val !== 'valid' && 'Value is invalid'));
store.dispatch(actions.validateErrors('test.foo',
(val) => val !== 'valid' && 'Value is invalid again'));
store.dispatch(actions.validateErrors('test.foo',
(val) => val !== 'bar' && 'This should return false'));
});
...
validateFields = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
model: 'test',
type: actionTypes.SET_FIELDS_VALIDITY,
options: {},
},
],
done);
const action = actions.validateFields('test', {
'': (val) => val.foo === 'bar',
foo: (val) => val === 'bar',
foo_valid: () => true,
foo_invalid: () => false,
with_keys: {
key_valid: () => true,
key_invalid: () => false,
...
validateFieldsErrors = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
options: {
errors: true,
},
},
],
done);
const action = actions.validateFieldsErrors('test', {
'': (val) => val.foo === 'invalid' && 'form is invalid',
foo: (val) => val === 'invalid' && 'foo is invalid',
foo_valid: () => false,
foo_invalid: () => 'foo_invalid is invalid',
with_keys: {
key_valid: () => false,
key_invalid: () => 'key_invalid is invalid',
...
xor = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
...
parser?: (value: any, previous?: any) => any;
/**
* An action creator (function) that specifies which action the <Field> component should use when dispatching a change
to the model.
*
* By default, this action is:
* * actions.change(model, value) for text input controls
* * actions.toggle(model, value) for checkboxes (single-value models)
* * actions.xor(model, value) for checkboxes (multi-value models)
*
* Notes:
* * Use changeAction to do any other custom actions whenever your value is to change.
* * Since changeAction expects an action creator and redux-thunk is used, you can asynchronously dispatch actions by returning
a thunk.
*
* @param model The model that is being changed
* @param value The value that the model is being changed to
...
function arraysEqual(firstArray, secondArray) { return firstArray && secondArray && firstArray.length === secondArray.length && firstArray.every(function (item, index) { return item === secondArray[index]; }); }
n/a
function assoc(state, key, value) { var newState = objClone(state); newState[key] = value; return newState; }
n/a
function assocIn(state, path, value) { var fn = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _identity2.default; if (!path.length) return value; var key0 = path[0]; if (path.length === 1) { return fn(assoc(state, key0, value)); } return fn(assoc(state, key0, assocIn(state[key0] || {}, path.slice(1), value, fn))); }
n/a
default = function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }
n/a
function dispatchBatchIfNeeded(model, actions, dispatch) { if (!actions.length) return void 0; var dispatchableActions = actions.filter(function (action) { return !!action; }); if (!dispatchableActions.length) return void 0; return dispatch(batch(model, dispatchableActions)); }
n/a
function createBatchReducer(reducer, initialState) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var transformAction = options.transformAction; return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; var transformedAction = transformAction ? transformAction(action) : action; if (transformedAction.type === _actionTypes2.default.BATCH) { return transformedAction.actions.reduce(reducer, state); } return reducer(state, transformedAction); }; }
n/a
function capitalize(string) { if (typeof string !== 'string') { return ''; } return string.charAt(0).toUpperCase() + string.slice(1); }
n/a
function changeActionReducer(state, action, localPath) { if (action.type !== _actionTypes2.default.CHANGE) return state; var field = (0, _get2.default)(state, localPath, (0, _formReducer.createInitialState)(action.model, action.value)); var updatedField = updateFieldValue(field, action); if (!localPath.length) return updatedField; var updatedState = (0, _assocIn2.default)(state, localPath, updatedField, function (form) { if (!form.$form) return form; var formValue = action.state ? (0, _get2.default)(action.state, form.$form.model) : (0, _getFormValue2.default)(form); var formUpdates = _extends({}, form.$form, { value: formValue }); if (action.silent) { formUpdates.loadedValue = formValue; } else { formUpdates.pristine = false; } return _extends({}, form, { $form: formUpdates }); }); return updatedState; }
n/a
function combineForms(forms) { var formReducerKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'forms'; var formKeys = Object.keys(forms); var modelReducers = {}; var initialFormState = {}; formKeys.forEach(function (formKey) { var formValue = forms[formKey]; if (typeof formValue === 'function') { var initialState = void 0; try { initialState = formValue(undefined, _nullAction2.default); } catch (error) { initialState = null; } modelReducers[formKey] = (0, _modeledEnhancer2.default)(formValue, formKey); initialFormState[formKey] = initialState; } else { modelReducers[formKey] = (0, _modelReducer2.default)(formKey, formValue); initialFormState[formKey] = formValue; } }); return (0, _redux2.default)(_extends({}, modelReducers, _defineProperty({}, formReducerKey, (0, _formReducer2.default)('', initialFormState )))); }
n/a
function compose() { for (var _len = arguments.length, reducers = Array(_len), _key = 0; _key < _len; _key++) { reducers[_key] = arguments[_key]; } return function (state, action) { return reducers.reduceRight(function (prevState, reducer) { return reducer(prevState, action); }, state); }; }
n/a
function containsEvent(events, event) { if (typeof events === 'string') { return events === event; } return !!~events.indexOf(event); }
n/a
function createControlClass() { var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategy; var emptyControlProps = {}; var emptyMapProps = {}; var Control = function (_Component) { _inherits(Control, _Component); function Control(props) { _classCallCheck(this, Control); var _this = _possibleConstructorReturn(this, (Control.__proto__ || Object.getPrototypeOf(Control)).call(this, props)); _this.getChangeAction = _this.getChangeAction.bind(_this); _this.getValidateAction = _this.getValidateAction.bind(_this); _this.handleKeyPress = _this.handleKeyPress.bind(_this); _this.createEventHandler = _this.createEventHandler.bind(_this); _this.handleFocus = _this.createEventHandler('focus').bind(_this); _this.handleBlur = _this.createEventHandler('blur').bind(_this); _this.handleUpdate = _this.createEventHandler('change').bind(_this); _this.handleChange = _this.handleChange.bind(_this); _this.handleLoad = _this.handleLoad.bind(_this); _this.getMappedProps = _this.getMappedProps.bind(_this); _this.attachNode = _this.attachNode.bind(_this); if (props.debounce) { _this.handleUpdate = (0, _debounce2.default)(_this.handleUpdate, props.debounce); } _this.willValidate = false; _this.state = { viewValue: props.modelValue }; return _this; } _createClass(Control, [{ key: 'componentDidMount', value: function componentDidMount() { this.attachNode(); this.handleLoad(); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(_ref) { var modelValue = _ref.modelValue; if (modelValue !== this.props.modelValue) { this.setViewValue(modelValue); } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { return !(0, _shallowEqual2.default)(this.props, nextProps, { deepKeys: ['controlProps'], omitKeys: ['mapProps'] }) || !(0, _shallowEqual2.default)(this.state.viewValue, nextState.viewValue); } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this.handleIntents(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var _props = this.props, model = _props.model, fieldValue = _props.fieldValue, dispatch = _props.dispatch, _props$validators = _props.validators, validators = _props$validators === undefined ? {} : _props$validators, _props$errors = _props.errors, errors = _props$errors === undefined ? {} : _props$errors, persist = _props.persist; if (!persist && fieldValue && !fieldValue.valid) { var keys = Object.keys(validators).concat(Object.keys(errors), this.willValidate ? _validityKeys2.default : []); dispatch(_actions2.default.resetValidity(model, keys)); } } }, { key: 'getMappedProps', value: function getMappedProps() { var props = this.props; var mapProps = props.mapProps; var viewValue = this.state.viewValue; var originalProps = _extends({}, props, props.controlProps, { onFocus: this.handleFocus, onBlur: this.handleBlur, onChange: this.handleChange, onKeyPress: this.handleKeyPress, viewValue: viewValue }); if ((0, _isPlainObject2.default)(mapProps)) { return (0, _mapValues2.default)(mapProps, function (value, key) { if (typeof value === 'function' && key !== 'component') { return value(originalProps); } return value; }); } else if (typeof mapProps === 'function') { return mapProps(originalProps); } return emptyMapProps; } }, { key: 'getChangeAction', value: functio ...
n/a
function DefaultConnectedControl() { _classCallCheck(this, DefaultConnectedControl); return _possibleConstructorReturn(this, (DefaultConnectedControl.__proto__ || Object.getPrototypeOf(DefaultConnectedControl)). apply(this, arguments)); }
n/a
function createFormState(model, values, customInitialFieldState) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var state = { $form: createFieldState(model, values, customInitialFieldState, options) }; if (options.lazy) return state; Object.assign(state, (0, _mapValues2.default)(values, function (value, key) { var subModel = getSubModelString(model, key); return fieldOrForm(subModel, value, customInitialFieldState); })); return state; }
n/a
function createFieldState(model, value, customInitialFieldState) { return _extends({}, _initialFieldState2.default, customInitialFieldState, { model: model, value: value, initialValue: value }); }
n/a
function fieldOrForm(model, value, customInitialFieldState) { // TODO: create toModel() var stringModel = Array.isArray(model) ? model.join('.') : model; if (Array.isArray(value) || (0, _isPlainObject2.default)(value)) { return createFormState(stringModel, value, customInitialFieldState); } return createFieldState(stringModel, value, customInitialFieldState); }
n/a
function getMeta(fieldLike, prop) { if (fieldLike && fieldLike.$form) return fieldLike.$form[prop]; return fieldLike[prop]; }
n/a
function updateFieldState(existingFieldState, updatedFieldState) { var newField = _extends({}, existingFieldState, updatedFieldState); return newField; }
n/a
function debounce(func, delay) { var timeout = void 0; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var later = function later() { timeout = null; func.apply(null, args); }; clearTimeout(timeout); timeout = setTimeout(later, delay); }; }
n/a
function compareChildren(props, nextProps) {
var children = props.children;
var nextChildren = nextProps.children;
// If the number of children changed, then children are different.
// If there are no children, use shallowCompare in parent function
// to determine if component should update (false && true == false)
if (_react2.default.Children.count(children) !== _react2.default.Children.count(nextChildren) || !_react2.default.Children.count
(children) || !_react2.default.Children.count(nextChildren)) {
return true;
}
var childrenArray = _react2.default.Children.toArray(children);
var nextChildrenArray = _react2.default.Children.toArray(nextChildren);
// React.Children.toArray strip's `false` children so lengths
// can change
if (childrenArray.length !== nextChildrenArray.length) {
return false;
}
return [].concat(childrenArray).some(function (child, i) {
var nextChild = nextChildrenArray[i];
if (!child.props || !nextChild.props) {
return !(0, _shallowEqual2.default)(child, nextChild);
}
/* eslint-disable no-use-before-define */
return deepCompareChildren(child, nextChild.props, nextChild.state);
});
}
n/a
function deepCompareChildren(instance, nextProps, nextState) { if (!instance.props.children) return (0, _shallowCompare2.default)(instance, nextProps, nextState); return (0, _shallowCompare2.default)(instance, nextProps, nextState) || compareChildren(instance.props, nextProps); }
n/a
function endsWith(string, subString) { if (typeof string !== 'string') return false; var lastIndex = string.lastIndexOf(subString); return lastIndex !== -1 && lastIndex + subString.length === string.length; }
n/a
function createErrorsClass() { var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategy; var Errors = function (_Component) { _inherits(Errors, _Component); function Errors() { _classCallCheck(this, Errors); return _possibleConstructorReturn(this, (Errors.__proto__ || Object.getPrototypeOf(Errors)).apply(this, arguments)); } _createClass(Errors, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { var fieldValue = nextProps.fieldValue, formValue = nextProps.formValue; var dynamic = this.props.dynamic; if (dynamic) { return !(0, _shallowEqual2.default)(this.props, nextProps); } return fieldValue !== this.props.fieldValue || formValue !== this.props.formValue; } }, { key: 'mapErrorMessages', value: function mapErrorMessages(errors) { var _this2 = this; var messages = this.props.messages; if (typeof errors === 'string') { return this.renderError(errors, 'error'); } if (!errors) return null; return (0, _map2.default)(errors, function (error, key) { var message = messages[key]; if (error) { if (message || typeof error === 'string') { return _this2.renderError(message || error, key); } else if ((0, _isPlainObject2.default)(error)) { return _this2.mapErrorMessages(error); } } return false; }).reduce(function (a, b) { return b ? a.concat(b) : a; }, []); } }, { key: 'renderError', value: function renderError(message, key) { var _props = this.props, component = _props.component, model = _props.model, modelValue = _props.modelValue, fieldValue = _props.fieldValue, errors = _props.fieldValue.errors; var errorProps = { key: key, model: model, modelValue: modelValue, fieldValue: fieldValue }; var messageString = typeof message === 'function' ? message(modelValue, errors[key]) : message; if (!messageString) return null; var allowedProps = typeof component === 'function' ? errorProps : { key: key }; return _react2.default.createElement(component, allowedProps, messageString); } }, { key: 'render', value: function render() { var _props2 = this.props, fieldValue = _props2.fieldValue, formValue = _props2.formValue, show = _props2.show, wrapper = _props2.wrapper; var allowedProps = typeof wrapper === 'function' ? this.props : (0, _omit2.default)(this.props, Object.keys(propTypes)); if (!showErrors(fieldValue, formValue, show)) { return null; } var errorMessages = (0, _isValid2.default)(fieldValue) ? null : this.mapErrorMessages(fieldValue.errors); if (!errorMessages) return null; return _react2.default.createElement(wrapper, allowedProps, errorMessages); } }]); return Errors; }(_react.Component); process.env.NODE_ENV !== "production" ? Errors.propTypes = propTypes : void 0; Errors.defaultProps = { wrapper: 'div', component: 'span', messages: {}, show: true, dynamic: true }; function mapStateToProps(state, _ref) { var model = _ref.model; var modelString = (0, _getModel2.default)(model, state); var form = s.getForm(state, modelString); (0, _invariant2.default)(form, 'Unable to retrieve errors. ' + 'Could not find form for "%s" in the store.', modelString); var formValue = form.$form; var fieldValue = s.getFieldFromState(state, modelString) || _initialFieldState2.default; return { model: modelString, modelValue: s.get(state, modelString), formValue: formValue, fieldValue: fieldValue }; } return (0, _resolveModel2.default)((0 ...
n/a
function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper)).call (this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; }
n/a
function createFieldActions() { var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategies; var addIntent = function addIntent(model, intent) { return { type: _actionTypes2.default.ADD_INTENT, model: model, intent: intent }; }; var clearIntents = function clearIntents(model, intents) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return { type: _actionTypes2.default.CLEAR_INTENTS, model: model, intents: intents, options: options }; }; var focus = function focus(model, value) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return _extends({ type: _actionTypes2.default.FOCUS, model: model, value: value }, options); }; var silentFocus = function silentFocus(model, value) { return focus(model, value, { silent: true }); }; var blur = function blur(model) { return { type: _actionTypes2.default.BLUR, model: model }; }; var setPristine = function setPristine(model) { return { type: _actionTypes2.default.SET_PRISTINE, model: model }; }; var setDirty = function setDirty(model) { return { type: _actionTypes2.default.SET_DIRTY, model: model }; }; var setInitial = function setInitial(model) { return { type: _actionTypes2.default.SET_INITIAL, model: model }; }; var setPending = function setPending(model) { var pending = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var options = arguments[2]; return _extends({ type: _actionTypes2.default.SET_PENDING, model: model, pending: pending }, options); }; var setValidating = function setValidating(model) { var validating = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; return { type: _actionTypes2.default.SET_VALIDATING, model: model, validating: validating }; }; var setValidity = function setValidity(model, validity) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return _extends({ type: options.errors ? _actionTypes2.default.SET_ERRORS : _actionTypes2.default.SET_VALIDITY, model: model }, options, _defineProperty({}, options.errors ? 'errors' : 'validity', validity)); }; var resetValidity = function resetValidity(model) { var omitKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { type: _actionTypes2.default.RESET_VALIDITY, model: model, omitKeys: omitKeys }; }; var setFieldsValidity = function setFieldsValidity(model, fieldsValidity) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return { type: _actionTypes2.default.SET_FIELDS_VALIDITY, model: model, fieldsValidity: fieldsValidity, options: options }; }; var setErrors = function setErrors(model, errors) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return setValidity(model, errors, _extends({}, options, { errors: true })); }; var setFieldsErrors = function setFieldsErrors(model, fieldsErrors, options) { return setFieldsValidity(model, fieldsErrors, _extends({}, options, { errors: true })); }; var resetErrors = resetValidity; var setTouched = function setTouched(model) { return { type: _actionTypes2.default.SET_TOUCHED, model: model }; }; var setUntouched = function setUntouched(model) { return { type: _actionTypes2.default.SET_UNTOUCHED, model: model }; }; var asyncSetValidity = function asyncSetValidity(model, validator) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return function (dispatch, getState) { var value = s.get(getState(), model); dispatch(setVa ...
n/a
function createFieldClass() { var customControlPropsMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultStrategy; // Use the fieldPropTypes if no controlProptypes have been defined to // maintain backwards compatibiltiy. var controlPropTypes = s.controlPropTypes || fieldPropTypes; function mapStateToProps(state, props) { var model = props.model; var modelString = (0, _getModel2.default)(model, state); var fieldValue = s.getFieldFromState(state, modelString) || _initialFieldState2.default; return { model: modelString, fieldValue: fieldValue }; } var options = { controlPropsMap: _extends({}, _controlPropsMap3.default, customControlPropsMap) }; // TODO: refactor var defaultControlPropsMap = { checkbox: { changeAction: s.actions.checkWithValue, getValue: _getValue.getCheckboxValue, isToggle: true }, radio: { isToggle: true } }; var Field = function (_Component) { _inherits(Field, _Component); function Field() { _classCallCheck(this, Field); return _possibleConstructorReturn(this, (Field.__proto__ || Object.getPrototypeOf(Field)).apply(this, arguments)); } _createClass(Field, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { var dynamic = this.props.dynamic; if (dynamic) { return (0, _deepCompareChildren2.default)(this, nextProps); } return (0, _shallowCompareWithoutChildren2.default)(this, nextProps); } }, { key: 'createControlComponent', value: function createControlComponent(control) { var props = this.props; if (!control || !control.props || control instanceof _controlComponent2.default) { return control; } var controlType = getControlType(control, props, options); var _props$mapProps = props.mapProps, mapProps = _props$mapProps === undefined ? options.controlPropsMap[controlType] : _props$mapProps; var controlProps = (0, _pick2.default)(props, Object.keys(controlPropTypes)); if (!mapProps) { return _react2.default.cloneElement(control, null, this.mapChildrenToControl(control.props.children)); } return _react2.default.createElement(s.Control, _extends({}, controlProps, { control: control, controlProps: control.props, component: control.type, mapProps: mapProps }, defaultControlPropsMap[controlType] || {})); } }, { key: 'mapChildrenToControl', value: function mapChildrenToControl(children) { var _this2 = this; if (_react2.default.Children.count(children) > 1) { return _react2.default.Children.map(children, function (child) { return _this2.createControlComponent(child); }); } return this.createControlComponent(children); } }, { key: 'render', value: function render() { var _props = this.props, component = _props.component, children = _props.children, fieldValue = _props.fieldValue; var allowedProps = (0, _omit2.default)(this.props, Object.keys(controlPropTypes)); var renderableChildren = typeof children === 'function' ? children(fieldValue) : children; if (!component) { (0, _invariant2.default)(_react2.default.Children.count(renderableChildren) === 1, 'Empty wrapper components for <Field > are only possible' + 'when there is a single child. Please check the children' + ('passed into <Field model="' + this.props.model + '">.')); return this.createControlComponent(renderableChildren); } return _react2.default.createElement(component, allowedProps, this.mapChildrenToControl(renderableChildren)); } }]); return Field; }(_react.Component); if (process.env.NODE_ENV !== 'production') ...
n/a
function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper)).call (this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; }
n/a
function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper)).call (this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; }
n/a
function find() { var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var predicate = arguments[1]; if (array.prototype.find) return array.find(predicate); var length = array.length >>> 0; for (var i = 0; i < length; i++) { var value = array[i]; if (predicate(value, i, array)) return value; } return undefined; }
n/a
function findKey(object, predicate) { var resultKey = void 0; Object.keys(object).some(function (key) { var isKey = predicate(object[key], key, object); if (isKey) { resultKey = key; return true; } return false; }); return resultKey; }
n/a
function flatten(data) { var result = {}; var delimiter = '.'; function recurse(cur) { var prop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; if (Object(cur) !== cur) { result[prop] = cur; } else if (Array.isArray(cur)) { if (!cur.length) result[prop] = []; cur.forEach(function (item, i) { recurse(cur[i], prop ? [prop, i].join(delimiter) : '' + i); }); } else { var isEmpty = true; Object.keys(cur).forEach(function (key) { isEmpty = false; recurse(cur[key], prop ? [prop, key].join(delimiter) : key); }); if (isEmpty) result[prop] = {}; } } recurse(data); return result; }
n/a
function createFormActionsReducer(options) { var formOptions = options ? _extends({}, defaultOptions, options, { initialFieldState: _extends({}, defaultOptions.initialFieldState, options.initialFieldState) }) : defaultOptions; var customInitialFieldState = formOptions.initialFieldState; return function formActionsReducer(state, action, localPath) { var _getFieldAndForm = (0, _updateField.getFieldAndForm)(state, localPath), _getFieldAndForm2 = _slicedToArray(_getFieldAndForm, 1), field = _getFieldAndForm2[0]; var fieldState = field && field.$form ? field.$form : field; var intents = fieldState.intents; var fieldUpdates = {}; var subFieldUpdates = {}; var parentFormUpdates = void 0; switch (action.type) { case _actionTypes2.default.FOCUS: { fieldUpdates = { focus: true, intents: action.silent ? intents : addIntent(intents, action) }; break; } case _actionTypes2.default.BLUR: case _actionTypes2.default.SET_TOUCHED: { var fieldForm = (0, _getFieldForm2.default)(state, localPath).$form; fieldUpdates = { focus: action.type === _actionTypes2.default.BLUR ? false : field.focus, touched: true, retouched: fieldForm ? !!(fieldForm.submitted || fieldForm.submitFailed) : false }; parentFormUpdates = { touched: true, retouched: fieldUpdates.retouched }; break; } case _actionTypes2.default.SET_UNTOUCHED: { fieldUpdates = { focus: false, touched: false }; break; } case _actionTypes2.default.SET_PRISTINE: case _actionTypes2.default.SET_DIRTY: { var pristine = action.type === _actionTypes2.default.SET_PRISTINE; fieldUpdates = { pristine: pristine }; subFieldUpdates = { pristine: pristine }; parentFormUpdates = function parentFormUpdates(form) { return { pristine: (0, _isPristine2.default)(form) }; }; break; } case _actionTypes2.default.SET_VALIDATING: { fieldUpdates = { validating: action.validating, validated: !action.validating }; break; } case _actionTypes2.default.SET_VALIDITY: case _actionTypes2.default.SET_ERRORS: { var _fieldUpdates; var isErrors = action.type === _actionTypes2.default.SET_ERRORS; var validity = void 0; if (isErrors) { validity = action.merge ? (0, _mergeValidity2.default)(fieldState.errors, action.errors) : action.errors; } else { validity = action.merge ? (0, _mergeValidity2.default)(fieldState.validity, action.validity) : action.validity; } var inverseValidity = (0, _isPlainObject2.default)(validity) ? (0, _mapValues2.default)(validity, _inverse2.default) : ! validity; // If the field is a form, its validity is // also based on whether its fields are all valid. var areFieldsValid = field && field.$form ? (0, _isValid.fieldsValid)(field, { async: false }) : true; fieldUpdates = (_fieldUpdates = {}, _defineProperty(_fieldUpdates, isErrors ? 'errors' : 'validity', validity), _defineProperty (_fieldUpdates, isErrors ? 'validity' : 'errors', inverseValidity), _defineProperty(_fieldUpdates, 'validating', false), _defineProperty (_fieldUpdates, 'validated', true), _defineProperty(_fieldUpdates, 'valid', areFieldsValid && (isErrors ? !(0, _isValidityInvalid2 .default)(validity) : (0, _isValidityValid2.default)(validity))), _fieldUpdates); if (action.async) { var actionValidity = isErrors ? action.errors : action.validity; fieldUpdates.asyncKeys = (0, _isPlainObject2.default)(actionValidity) || Array.isArray(actionValidity) ? Object.keys (actio ...
n/a
function formActionsReducer(state, action, localPath) { var _getFieldAndForm = (0, _updateField.getFieldAndForm)(state, localPath), _getFieldAndForm2 = _slicedToArray(_getFieldAndForm, 1), field = _getFieldAndForm2[0]; var fieldState = field && field.$form ? field.$form : field; var intents = fieldState.intents; var fieldUpdates = {}; var subFieldUpdates = {}; var parentFormUpdates = void 0; switch (action.type) { case _actionTypes2.default.FOCUS: { fieldUpdates = { focus: true, intents: action.silent ? intents : addIntent(intents, action) }; break; } case _actionTypes2.default.BLUR: case _actionTypes2.default.SET_TOUCHED: { var fieldForm = (0, _getFieldForm2.default)(state, localPath).$form; fieldUpdates = { focus: action.type === _actionTypes2.default.BLUR ? false : field.focus, touched: true, retouched: fieldForm ? !!(fieldForm.submitted || fieldForm.submitFailed) : false }; parentFormUpdates = { touched: true, retouched: fieldUpdates.retouched }; break; } case _actionTypes2.default.SET_UNTOUCHED: { fieldUpdates = { focus: false, touched: false }; break; } case _actionTypes2.default.SET_PRISTINE: case _actionTypes2.default.SET_DIRTY: { var pristine = action.type === _actionTypes2.default.SET_PRISTINE; fieldUpdates = { pristine: pristine }; subFieldUpdates = { pristine: pristine }; parentFormUpdates = function parentFormUpdates(form) { return { pristine: (0, _isPristine2.default)(form) }; }; break; } case _actionTypes2.default.SET_VALIDATING: { fieldUpdates = { validating: action.validating, validated: !action.validating }; break; } case _actionTypes2.default.SET_VALIDITY: case _actionTypes2.default.SET_ERRORS: { var _fieldUpdates; var isErrors = action.type === _actionTypes2.default.SET_ERRORS; var validity = void 0; if (isErrors) { validity = action.merge ? (0, _mergeValidity2.default)(fieldState.errors, action.errors) : action.errors; } else { validity = action.merge ? (0, _mergeValidity2.default)(fieldState.validity, action.validity) : action.validity; } var inverseValidity = (0, _isPlainObject2.default)(validity) ? (0, _mapValues2.default)(validity, _inverse2.default) : ! validity; // If the field is a form, its validity is // also based on whether its fields are all valid. var areFieldsValid = field && field.$form ? (0, _isValid.fieldsValid)(field, { async: false }) : true; fieldUpdates = (_fieldUpdates = {}, _defineProperty(_fieldUpdates, isErrors ? 'errors' : 'validity', validity), _defineProperty (_fieldUpdates, isErrors ? 'validity' : 'errors', inverseValidity), _defineProperty(_fieldUpdates, 'validating', false), _defineProperty (_fieldUpdates, 'validated', true), _defineProperty(_fieldUpdates, 'valid', areFieldsValid && (isErrors ? !(0, _isValidityInvalid2 .default)(validity) : (0, _isValidityValid2.default)(validity))), _fieldUpdates); if (action.async) { var actionValidity = isErrors ? action.errors : action.validity; fieldUpdates.asyncKeys = (0, _isPlainObject2.default)(actionValidity) || Array.isArray(actionValidity) ? Object.keys(actionValidity ) : true; } parentFormUpdates = function parentFormUpdates(form) { return { valid: (0, _isValid2.default)(form) }; }; break; } case _actionTypes2.default.SET_FIELDS_VALIDITY: { return (0, _map2.default)(action.fieldsValidity, function (fieldValidity, subField) { return _fieldActions2.default.setValidity(subField, fieldValidity, action.options); }).reduce(function (accState, ...
n/a
function createFormClass() { var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategy; var Form = function (_Component) { _inherits(Form, _Component); function Form(props) { _classCallCheck(this, Form); var _this = _possibleConstructorReturn(this, (Form.__proto__ || Object.getPrototypeOf(Form)).call(this, props)); _this.handleSubmit = _this.handleSubmit.bind(_this); _this.handleReset = _this.handleReset.bind(_this); _this.handleValidSubmit = _this.handleValidSubmit.bind(_this); _this.handleInvalidSubmit = _this.handleInvalidSubmit.bind(_this); _this.attachNode = _this.attachNode.bind(_this); _this.state = { lastSubmitEvent: null }; return _this; } _createClass(Form, [{ key: 'getChildContext', value: function getChildContext() { return { model: this.props.model, localStore: this.props.store }; } }, { key: 'componentDidMount', value: function componentDidMount() { this.handleUpdate(); this.handleChange(); if ((0, _containsEvent2.default)(this.props.validateOn, 'change')) { this.validate(this.props, true); } if (this.props.getDispatch) { this.props.getDispatch(this.props.dispatch); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if ((0, _containsEvent2.default)(nextProps.validateOn, 'change')) { this.validate(nextProps); } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { return (0, _deepCompareChildren2.default)(this, nextProps); } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { this.handleIntents(); if (!(0, _shallowEqual2.default)(prevProps.formValue, this.props.formValue)) { this.handleUpdate(); } if (!(0, _shallowEqual2.default)(prevProps.modelValue, this.props.modelValue)) { this.handleChange(); } } }, { key: 'handleUpdate', value: function handleUpdate() { if (this.props.onUpdate) { this.props.onUpdate(this.props.formValue); } } }, { key: 'handleChange', value: function handleChange() { if (this.props.onChange) { this.props.onChange(this.props.modelValue); } } }, { key: 'attachNode', value: function attachNode(node) { if (!node) return; this._node = node; this._node.submit = this.handleSubmit; if (this.props.getRef) this.props.getRef(node); } }, { key: 'validate', value: function validate(nextProps) { var _this2 = this; var initial = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var submit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var _props = this.props, model = _props.model, dispatch = _props.dispatch, formValue = _props.formValue, modelValue = _props.modelValue; var validators = nextProps.validators, errors = nextProps.errors; if (!formValue) return; if (!validators && !errors && modelValue !== nextProps.modelValue) { return; } var validatorsChanged = validators !== this.props.validators || errors !== this.props.errors; var fieldKeys = (validators ? Object.keys(validators) : []).concat(errors ? Object.keys(errors) : []); var fieldsErrors = {}; var validityChanged = false; var keysToValidate = []; fieldKeys.forEach(function (key) { if (!!~keysToValidate.indexOf(key)) return; var valuesChanged = key === '' ? modelValue !== nextProps.modelValue : s.get(modelValue, key) !== s.get(nextProps.modelValue , key); if (submit || init ...
n/a
function Connect(props, context) { _classCallCheck(this, Connect); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.version = version; _this.store = props.store || context.store; (0, _invariant2["default"])(_this.store, 'Could not find "store" in either the context or ' + ('props of "' + connectDisplayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + connectDisplayName + '".')); var storeState = _this.store.getState(); _this.state = { storeState: storeState }; _this.clearCache(); return _this; }
n/a
function createInitialState(model, state) { var customInitialFieldState = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (Array.isArray(state) || (0, _isPlainObject2.default)(state)) { return (0, _createField.createFormState)(model, state, customInitialFieldState, options); } return (0, _createField2.default)(model, state, customInitialFieldState, options); }
n/a
function createFormReducer(model) { var initialState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _options$plugins = options.plugins, plugins = _options$plugins === undefined ? [] : _options$plugins, customInitialFieldState = options.initialFieldState, _options$transformAct = options.transformAction, transformAction = _options$transformAct === undefined ? null : _options$transformAct; var modelPath = (0, _toPath2.default)(model); var initialFormState = createInitialState(model, initialState, customInitialFieldState, options); var defaultPlugins = [(0, _formActionsReducer.createFormActionsReducer)({ initialFieldState: customInitialFieldState }), _changeActionReducer2 .default]; var wrappedPlugins = plugins.concat(defaultPlugins).map(function (plugin) { return wrapFormReducer(plugin, modelPath, initialFormState); }); return (0, _batchedEnhancer2.default)(_composeReducers2.default.apply(undefined, _toConsumableArray(wrappedPlugins)), undefined , { transformAction: transformAction }); }
n/a
function createFormCombiner() { var strategy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategy; function createForms(forms) { var model = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var formKeys = Object.keys(forms); var modelReducers = {}; var initialFormState = {}; var optionsWithDefaults = _extends({}, defaults, options); var key = optionsWithDefaults.key, plugins = optionsWithDefaults.plugins, formOptions = _objectWithoutProperties(optionsWithDefaults, ['key', 'plugins']); var cacheId = cacheModelState({}); formKeys.forEach(function (formKey) { var formValue = forms[formKey]; var subModel = getSubModelString(model, formKey); if (typeof formValue === 'function') { var initialState = void 0; try { initialState = formValue(undefined, _nullAction2.default); } catch (error) { initialState = null; } modelReducers[formKey] = cacheReducer(strategy.modeled(formValue, subModel), subModel, cacheId); initialFormState[formKey] = initialState; } else { modelReducers[formKey] = cacheReducer(strategy.modelReducer(subModel, formValue), subModel, cacheId); initialFormState[formKey] = strategy.toJS(formValue); } }); return _extends({}, modelReducers, _defineProperty({}, key, function (state, action) { return strategy.formReducer(model, initialFormState, _extends({ plugins: plugins }, formOptions))(state, _extends({}, action, { state: Object.assign({}, modelCache[cacheId]) })); })); } function combineForms(forms) { var model = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var mappedReducers = createForms(forms, model, options); return (0, _redux.combineReducers)(mappedReducers); } return { createForms: createForms, combineForms: combineForms }; }
n/a
function createForms(forms) { var model = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var formKeys = Object.keys(forms); var modelReducers = {}; var initialFormState = {}; var optionsWithDefaults = _extends({}, defaults, options); var key = optionsWithDefaults.key, plugins = optionsWithDefaults.plugins, formOptions = _objectWithoutProperties(optionsWithDefaults, ['key', 'plugins']); var cacheId = cacheModelState({}); formKeys.forEach(function (formKey) { var formValue = forms[formKey]; var subModel = getSubModelString(model, formKey); if (typeof formValue === 'function') { var initialState = void 0; try { initialState = formValue(undefined, _nullAction2.default); } catch (error) { initialState = null; } modelReducers[formKey] = cacheReducer(strategy.modeled(formValue, subModel), subModel, cacheId); initialFormState[formKey] = initialState; } else { modelReducers[formKey] = cacheReducer(strategy.modelReducer(subModel, formValue), subModel, cacheId); initialFormState[formKey] = strategy.toJS(formValue); } }); return _extends({}, modelReducers, _defineProperty({}, key, function (state, action) { return strategy.formReducer(model, initialFormState, _extends({ plugins: plugins }, formOptions))(state, _extends({}, action, { state: Object.assign({}, modelCache[cacheId]) })); })); }
...
// set initial state with Immutable Map
const initialUserState = Immutable.fromJS({
firstName: '',
lastName: '',
});
const store = applyMiddleware(thunk)(createStore)(combineReducers({
...createForms({
user: initialUserState,
})
}));
export default store;
...
function combineForms(forms) { var model = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var mappedReducers = createForms(forms, model, options); return (0, _redux.combineReducers)(mappedReducers); }
n/a
function get(object, path, defaultValue) { var modelString = path; if (typeof path === 'number') { var result = object[path]; return result === undefined ? defaultValue : result; } if (!path.length) return object; if ((0, _endsWith2.default)(modelString, '.')) { modelString = modelString.slice(0, -1); } else if ((0, _endsWith2.default)(modelString, '[]')) { modelString = modelString.slice(0, -2); } return (0, _lodash2.default)(object, modelString, defaultValue); }
n/a
function getField(state, path) { if (process.env.NODE_ENV !== 'production') { if (!(0, _isPlainObject2.default)(state)) { throw new Error('Could not retrieve field \'' + path + '\' ' + 'from an invalid/empty form state.'); } } var result = (0, _get2.default)(state, path, _initialFieldState2.default); if ('$form' in result) return result.$form; return result; }
n/a
function getFieldForm(state, path) { var formPath = path.slice(0, -1); if (!formPath.length) return state; var form = (0, _get2.default)(state, formPath); (0, _invariant2.default)(form, 'Could not find form for "%s" in the store.', formPath.join('.')); return form; }
n/a
function getFieldFromState(state, modelString) { var s = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultStrategy; var form = state && '$form' in state ? state : s.getForm(state, modelString); if (!form || !form.$form) return null; if (!modelString.length) return form; (0, _invariant2.default)(form, 'Could not find form for "%s" in the store.', modelString); var formPath = (0, _toPath2.default)(form.$form.model); var fieldPath = (0, _toPath2.default)(modelString).slice(formPath.length); var field = (0, _get2.default)(form, fieldPath); if (!field) return null; if ((0, _isPlainObject2.default)(field) && '$form' in field) return field.$form; return field; }
n/a
function clearGetFormCache() { return formStateKeyCache = {}; }
n/a
function getForm(state, modelString) { var s = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultStrategy; var formStateKey = getFormStateKeyCached(state, modelString, s); if (!formStateKey) { return null; } var form = s.get(state, formStateKey); return form; }
n/a
function getFormStateKey(state, model) { var s = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultStrategy; var currentPath = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; var deepCandidateKeys = []; var result = null; s.keys(state).some(function (key) { var subState = s.get(state, key); if (subState && s.get(subState, '$form')) { var subStateModel = s.get(subState, '$form.model'); if ((0, _pathStartsWith2.default)(model, subStateModel) || subStateModel === '') { var _ret = function () { var localPath = (0, _pathStartsWith.pathDifference)(model, subStateModel); var resultPath = [currentPath, key]; var currentState = subState; localPath.every(function (segment) { if (s.get(currentState, segment) && s.get(currentState, segment + '.$form')) { currentState = s.get(currentState, segment); resultPath.push(segment); return true; } return false; }); result = joinPaths.apply(undefined, resultPath); return { v: true }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } return false; } if (s.isObject(subState)) { deepCandidateKeys.push(key); } return false; }); if (result) return result; deepCandidateKeys.some(function (key) { result = getFormStateKey(s.get(state, key), model, s, joinPaths(currentPath, key)); return !!result; }); if (result) return result; return null; }
n/a
function getFormValue(form) { if (form && !form.$form) { return typeof form.loadedValue !== 'undefined' ? form.loadedValue : form.initialValue; } var result = (0, _mapValues2.default)(form, function (field, key) { if (key === '$form') return undefined; return getFormValue(field); }); delete result.$form; return result; }
n/a
function immutableGetFromState(state, modelString) { var path = (0, _toPath2.default)(modelString); return path.reduce(function (subState, subPath) { if (!subState || typeof subState === 'string') return subState; // Current subState is immutable if ((typeof subState === 'undefined' ? 'undefined' : _typeof(subState)) === 'object' && 'get' in subState) { return subState.get(subPath); } // Current subState is a plain object/array return subState[subPath]; }, state); }
n/a
function getModel(model, state) { return typeof model === 'function' && state ? model(state) : model; }
n/a
function getValidity(validators, value) { var modelValue = (0, _getValue2.default)(value); if (typeof validators === 'function') { return validators(modelValue); } return (0, _mapValues2.default)(validators, function (validator) { return getValidity(validator, modelValue); }); }
n/a
function getValue(value) { return isEvent(value) ? getEventValue(value) : value; }
n/a
function getCheckboxValue(_, props) { var controlProps = props.controlProps; if ((0, _isMulti2.default)(props.model)) { return controlProps.value; } return !props.modelValue; }
n/a
function identity(a) { return a; }
n/a
function inverse(value) { return !value; }
n/a
function invertValidators(validators) { if (typeof validators === 'function') { return function (val) { return (0, _invertValidity2.default)(validators(val)); }; } return (0, _mapValues2.default)(validators, invertValidators); }
n/a
function invertValidity(validity) { if ((0, _isPlainObject2.default)(validity)) { return (0, _mapValues2.default)(validity, invertValidity); } return !validity; }
n/a
function isMulti(model) { return (0, _endsWith2.default)(model, '[]'); }
n/a
function isPending(formState) { if (!formState) return false; // Field is pending if (!formState.$form) { return formState.pending; } // Any field in form is pending return Object.keys(formState).some(function (key) { return isPending(formState[key]); }); }
n/a
function isPlainObject(o) { if (isObjectObject(o) === false) return false; // If has modified constructor var ctor = o.constructor; if (typeof ctor !== 'function') return false; // If has modified prototype var prot = ctor.prototype; if (isObjectObject(prot) === false) return false; // If constructor does not have an Object-specific method if (prot.hasOwnProperty('isPrototypeOf') === false) { return false; } // Most likely a plain Object return true; }
n/a
function isPristine(formState) { if (!formState) return false; // Form is pristine if (!formState.$form) { return formState.pristine; } // Every field in form is pristine return Object.keys(formState).every(function (key) { if (key === '$form') return true; return isPristine(formState[key]); }); }
n/a
function isRetouched(formState) { if (!formState) return false; // Field is pending if (!formState.$form) { return formState.retouched; } // Any field in form is pending return Object.keys(formState).some(function (key) { return isRetouched(formState[key]); }); }
n/a
function isTouched(formState) { if (!formState) return false; // Field is touched if (!formState.$form) { return formState.touched; } // Any field in form is touched return Object.keys(formState).some(function (key) { return isTouched(formState[key]); }); }
n/a
function isValid(formState) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { async: true }; if (!formState) return true; if (!formState.$form) { var errors = formState.errors; if (!Array.isArray(errors) && !(0, _isPlainObject2.default)(errors)) { // If asyncKeys = true and the error is not an // array or object (e.g. string), form errors are entirely async // and should be ignored when async = true. return !options.async && formState.asyncKeys || !errors; } return Object.keys(formState.errors).every(function (errorKey) { // if specified to ignore async validator keys and // current error key is an async validator key, // treat key as valid if (!options.async && formState.asyncKeys && !!~formState.asyncKeys.indexOf(errorKey)) { return true; } var valid = !formState.errors[errorKey]; return valid; }); } return Object.keys(formState).every(function (key) { return isValid(formState[key], options); }); }
n/a
function fieldsValid(formState) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { async: true }; return Object.keys(formState).every(function (key) { return key === '$form' || isValid(formState[key], options); }); }
n/a
function isValidityInvalid(errors) { if (Array.isArray(errors)) { return errors.some(isValidityInvalid); } if ((0, _isPlainObject2.default)(errors)) { return Object.keys(errors).some(function (key) { return isValidityInvalid(errors[key]); }); } return !!errors; }
n/a
function isValidityValid(validity) { if ((0, _isPlainObject2.default)(validity)) { return Object.keys(validity).every(function (key) { return isValidityValid(validity[key]); }); } return !!validity; }
n/a
function iteratee(value) { if (typeof value === 'function') { return value; } if (value === null) { return _identity2.default; } if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { return matcher(value); } return propChecker(value); }
n/a
function iterateeValue(data, value) { if (typeof value === 'function') { return value(data); } if (!Array.isArray(value) && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object' && typeof value !== 'string ') { return !!value; } return iteratee(value)(data); }
n/a
function LocalForm(props) { _classCallCheck(this, LocalForm); var _this = _possibleConstructorReturn(this, (LocalForm.__proto__ || Object.getPrototypeOf(LocalForm)).call(this, props)); _this.store = props.store || (0, _redux.createStore)((0, _formsReducer2.default)(_defineProperty({}, props.model, props.initialState ))); _this.dispatch = function (action) { if (typeof action === 'function') { return action(_this.store.dispatch, _this.store.getState); } return _this.store.dispatch(action); }; return _this; }
n/a
function map(values, iteratee) { if (Array.isArray(values)) { return values.map(iteratee); } var result = Object.keys(values).map(function (key) { return iteratee(values[key], key, values); }); return result; }
n/a
function mapValues(object, iteratee) { var result = {}; Object.keys(object || {}).forEach(function (key) { result[key] = iteratee(object[key], key, object); }); return result; }
n/a
function mergeDeep(target, source) { return _icepick2.default.merge(target, source); }
n/a
function mergeValidity(fieldValidity, actionValidity) { if (!(0, _isPlainObject2.default)(fieldValidity) || !(0, _isPlainObject2.default)(actionValidity)) { // can't merge string/boolean validity with keyed validity return actionValidity; } return (0, _merge2.default)(_extends({}, fieldValidity), actionValidity); }
n/a
function createModelActions() { var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategies; var change = function change(model, value) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; // option defaults var changeOptions = _extends({ silent: false, multi: (0, _isMulti2.default)(model), external: true }, options); if (typeof value === 'function') { return function (dispatch, getState) { var modelValue = s.get(getState(), model); return dispatch(change(model, value(modelValue), options)); }; } return _extends({ type: _actionTypes2.default.CHANGE, model: model, value: s.getValue(value) }, changeOptions); }; function createModifierAction(modifier, defaultValue, optionsIndex, getOptions) { var actionCreator = function actionCreator(model) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return function (dispatch, getState) { var modelValue = s.get(getState(), model, defaultValue); var value = modifier.apply(undefined, [modelValue].concat(args)); var options = getOptions ? getOptions.apply(undefined, [value].concat(args)) : undefined; dispatch(change(model, value, optionsFromArgs(args, optionsIndex - 1, options))); }; }; return actionCreator; } var xor = createModifierAction(function (value, item) { var iteratee = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (_item) { return _item === item; }; var valueWithoutItem = value.filter(function (_item) { return !iteratee(_item); }); return s.length(value) === s.length(valueWithoutItem) ? [].concat(_toConsumableArray(value), [item]) : valueWithoutItem; }, s.array, 3); var push = createModifierAction(function (value, item) { return s.push(value || s.array, item); }, s.array, 2); var toggle = createModifierAction(function (value) { return !value; }, undefined, 1); var checkWithValue = function checkWithValue(model, value) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var currentValue = options.currentValue; if ((0, _isMulti2.default)(model)) { var valueWithItem = currentValue || s.array; var valueWithoutItem = (valueWithItem || s.array).filter(function (item) { return item !== value; }); var multiValue = s.length(valueWithoutItem) === s.length(valueWithItem) ? s.push(valueWithItem, value) : valueWithoutItem; return change(model, multiValue); } return change(model, !currentValue); }; var check = function check(model, value) { return function (dispatch, getState) { var modelValue = s.get(getState(), model); var action = checkWithValue(model, value, { currentValue: modelValue }); dispatch(action); }; }; var filter = createModifierAction(function (value, iteratee) { return value.filter(iteratee); }, s.array, 2); var reset = function reset(model) { return { type: _actionTypes2.default.RESET, model: model }; }; var map = createModifierAction(function (value) { var iteratee = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _identity2.default; return value.map(iteratee); }, s.array, 2); var remove = createModifierAction(function (value, index) { return s.splice(value, index, 1); }, s.array, 2, function (_, index) { return { removeKeys: [index] }; }); var move = createModifierAction(function (value, indexFrom, indexTo) { if (indexFrom >= s.length(value) || indexTo >= s.length(value)) { throw new Error('Error moving array item: invalid bounds ' + indexFrom + ', ' + indexTo); } var item = s.get(value, indexFrom); var removed = s.splice(value, indexFrom, 1); var inserted = s.splice(removed, ind ...
n/a
function createModeler() { var strategy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategy; var getter = strategy.get, setter = strategy.set, object = strategy.object; return function _createModelReducer(model) { var initialState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : object; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var modelPath = (0, _toPath2.default)(model); var modelReducer = function modelReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; if (!action.model) { return state; } var path = (0, _toPath2.default)(action.model); if (!(0, _arraysEqual2.default)(path.slice(0, modelPath.length), modelPath)) { return state; } var localPath = path.slice(modelPath.length); switch (action.type) { case _actionTypes2.default.CHANGE: case _actionTypes2.default.LOAD: if (!localPath.length) { return action.value; } if (getter(state, localPath) === action.value) { return state; } return setter(state, localPath, action.value); case _actionTypes2.default.RESET: if (!localPath.length) { return initialState; } if (getter(state, localPath) === getter(initialState, localPath)) { return state; } return setter(state, localPath, getter(initialState, localPath)); default: return state; } }; return (0, _batchedEnhancer2.default)(modelReducer, initialState, options); }; }
n/a
function _createModelReducer(model) { var initialState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : object; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var modelPath = (0, _toPath2.default)(model); var modelReducer = function modelReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; if (!action.model) { return state; } var path = (0, _toPath2.default)(action.model); if (!(0, _arraysEqual2.default)(path.slice(0, modelPath.length), modelPath)) { return state; } var localPath = path.slice(modelPath.length); switch (action.type) { case _actionTypes2.default.CHANGE: case _actionTypes2.default.LOAD: if (!localPath.length) { return action.value; } if (getter(state, localPath) === action.value) { return state; } return setter(state, localPath, action.value); case _actionTypes2.default.RESET: if (!localPath.length) { return initialState; } if (getter(state, localPath) === getter(initialState, localPath)) { return state; } return setter(state, localPath, getter(initialState, localPath)); default: return state; } }; return (0, _batchedEnhancer2.default)(modelReducer, initialState, options); }
n/a
function createModelReducerEnhancer() { var modelReducerCreator = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _modelReducer3.default; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return function modelReducerEnhancer(reducer, model) { var initialState = void 0; try { initialState = reducer(undefined, _nullAction2.default); } catch (error) { initialState = null; } var _modelReducer = modelReducerCreator(model, initialState, options); return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; var updatedState = _modelReducer(state, action); return reducer(updatedState, action); }; }; }
n/a
function modelReducerEnhancer(reducer, model) { var initialState = void 0; try { initialState = reducer(undefined, _nullAction2.default); } catch (error) { initialState = null; } var _modelReducer = modelReducerCreator(model, initialState, options); return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; var updatedState = _modelReducer(state, action); return reducer(updatedState, action); }; }
n/a
function omit(object, props) { if (object == null) { return {}; } var newObject = _extends({}, object); if (typeof props === 'string') { delete newObject[props]; } else { props.forEach(function (prop) { delete newObject[prop]; }); } return newObject; }
n/a
function partition(collection, predicate) { var result = [[], []]; collection.forEach(function (item, index) { if (predicate(item, index, collection)) { result[0].push(item); } else { result[1].push(item); } }); return result; }
n/a
function pathStartsWith(pathString, subPathString) { if (pathString === subPathString) return true; var path = (0, _lodash2.default)(pathString); var subPath = (0, _lodash2.default)(subPathString); var startsWithSubPath = subPath.every(function (segment, index) { return path[index] === segment; }); return startsWithSubPath; }
n/a
function pathDifference(pathString, subPathString) { if (pathString === subPathString) return []; var path = (0, _lodash2.default)(pathString); var subPath = (0, _lodash2.default)(subPathString); var difference = path.reduce(function (acc, segment, index) { if (segment === subPath[index]) return acc; acc.push(segment); return acc; }, []); return difference; }
n/a
function persistEventWithCallback(callback) { return function (event) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (event && event.persist) { event.persist(); } callback.apply(undefined, [event].concat(args)); return event; }; }
n/a
function pick(object, props) { var result = {}; for (var i = 0; i < props.length; i++) { var prop = props[i]; result[prop] = object[prop]; } return result; }
n/a
function wrapWithModelResolver(WrappedComponent) { var deepKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var omitKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var ResolvedModelWrapper = function (_ReactComponent) { _inherits(ResolvedModelWrapper, _ReactComponent); function ResolvedModelWrapper(props, context) { _classCallCheck(this, ResolvedModelWrapper); var _this = _possibleConstructorReturn(this, (ResolvedModelWrapper.__proto__ || Object.getPrototypeOf(ResolvedModelWrapper )).call(this, props, context)); _this.model = context.model; _this.store = context.localStore; _this.deepKeys = deepKeys; _this.omitKeys = omitKeys; return _this; } _createClass(ResolvedModelWrapper, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { return !(0, _shallowEqual2.default)(this.props, nextProps, { deepKeys: this.deepKeys, omitKeys: this.omitKeys }); } }, { key: 'render', value: function render() { var resolvedModel = resolveModel(this.props.model, this.model); return _react2.default.createElement(WrappedComponent, _extends({}, this.props, { model: resolvedModel, store: this.store || undefined })); } }]); return ResolvedModelWrapper; }(ReactComponent); ResolvedModelWrapper.displayName = 'Modeled(' + WrappedComponent.displayName + ')'; ResolvedModelWrapper.propTypes = { model: _propTypes2.default.any }; ResolvedModelWrapper.contextTypes = { model: _propTypes2.default.any, localStore: _propTypes2.default.shape({ subscribe: _propTypes2.default.func, dispatch: _propTypes2.default.func, getState: _propTypes2.default.func }) }; return ResolvedModelWrapper; }
n/a
function shallowCompareWithoutChildren(instance, nextProps) { return !(0, _shallowEqual2.default)(instance.props, nextProps, { omitKeys: ['children'] }) || _react.Children.count(instance.props .children) !== _react.Children.count(nextProps.children); }
n/a
function shallowEqual(objA, objB) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (is(objA, objB)) { return true; } if ((typeof objA === 'undefined' ? 'undefined' : _typeof(objA)) !== 'object' || objA === null || (typeof objB === 'undefined' ? ' undefined' : _typeof(objB)) !== 'object' || objB === null) { return false; } if (objA instanceof Date && objB instanceof Date) { return objA === objB; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } var omitKeys = options.omitKeys, deepKeys = options.deepKeys; // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { // if key is an omitted key, skip comparison if (omitKeys && omitKeys.length && ~omitKeys.indexOf(keysA[i])) continue; if (deepKeys && deepKeys.length && ~deepKeys.indexOf(keysA[i])) { var result = shallowEqual(objA[keysA[i]], objB[keysA[i]]); if (!result) return false; } else if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; }
n/a
function toPath(value) { var path = value; if ((0, _endsWith2.default)(path, '.')) { path = path.slice(0, -1); } else if ((0, _endsWith2.default)(path, '[]')) { path = path.slice(0, -2); } return (0, _lodash2.default)(path); }
n/a
function createTrack() { var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultStrategy; return function track(model) { for (var _len = arguments.length, predicates = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { predicates[_key - 1] = arguments[_key]; } var isPartial = model[0] === '.'; return function (fullState, parentModel) { var childModel = isPartial ? model.slice(1) : model; var state = isPartial ? s.get(fullState, parentModel) : fullState; var _childModel$split = childModel.split(/\[\]\.?/), _childModel$split2 = _toArray(_childModel$split), parentModelPath = _childModel$split2[0], childModelPaths = _childModel$split2.slice(1); var fullPath = parentModelPath; var subState = s.get(state, fullPath); predicates.forEach(function (predicate, i) { var childModelPath = childModelPaths[i]; var predicateIteratee = (0, _iteratee2.default)(predicate); var subPath = childModelPath ? (0, _findKey2.default)(subState, predicateIteratee) + '.' + childModelPath : '' + (0, _findKey2 .default)(subState, predicateIteratee); subState = s.get(subState, subPath); fullPath += '.' + subPath; }); if ((0, _isMulti2.default)(childModel) && predicates.length < childModelPaths.length) { fullPath += '[]'; } return isPartial ? parentModel + '.' + fullPath : fullPath; }; }; }
n/a
function track(model) { for (var _len = arguments.length, predicates = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { predicates[_key - 1] = arguments[_key]; } var isPartial = model[0] === '.'; return function (fullState, parentModel) { var childModel = isPartial ? model.slice(1) : model; var state = isPartial ? s.get(fullState, parentModel) : fullState; var _childModel$split = childModel.split(/\[\]\.?/), _childModel$split2 = _toArray(_childModel$split), parentModelPath = _childModel$split2[0], childModelPaths = _childModel$split2.slice(1); var fullPath = parentModelPath; var subState = s.get(state, fullPath); predicates.forEach(function (predicate, i) { var childModelPath = childModelPaths[i]; var predicateIteratee = (0, _iteratee2.default)(predicate); var subPath = childModelPath ? (0, _findKey2.default)(subState, predicateIteratee) + '.' + childModelPath : '' + (0, _findKey2 .default)(subState, predicateIteratee); subState = s.get(subState, subPath); fullPath += '.' + subPath; }); if ((0, _isMulti2.default)(childModel) && predicates.length < childModelPaths.length) { fullPath += '[]'; } return isPartial ? parentModel + '.' + fullPath : fullPath; }; }
n/a
function trackable(actionCreator) { return function (model) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (typeof model === 'function') { return function (dispatch, getState) { var modelPath = model(getState()); dispatch(actionCreator.apply(undefined, [modelPath].concat(args))); }; } return actionCreator.apply(undefined, [model].concat(args)); }; }
n/a
function updateField(state, path, newState, newSubState, updater) { var _getFieldAndForm = getFieldAndForm(state, path), _getFieldAndForm2 = _slicedToArray(_getFieldAndForm, 2), field = _getFieldAndForm2[0], fullState = _getFieldAndForm2[1]; if (!field) return state; var isForm = field.hasOwnProperty('$form'); var fieldPath = isForm ? [].concat(_toConsumableArray(path), ['$form']) : path; var fieldState = isForm ? field.$form : field; var updatedFieldState = typeof newState === 'function' ? newState(fieldState) : newState; if (isForm && newSubState) { var formState = (0, _mapValues2.default)(field, function (subState, key) { if (key === '$form') { return (0, _createField.updateFieldState)(fieldState, updatedFieldState); } var updatedSubState = typeof newSubState === 'function' ? newSubState(subState, updatedFieldState) : newSubState; return (0, _createField.updateFieldState)(subState, updatedSubState); }); if (!path.length) return formState; return (0, _assocIn2.default)(fullState, path, formState, updater); } return (0, _assocIn2.default)(fullState, fieldPath, (0, _createField.updateFieldState)(fieldState, updatedFieldState), updater ); }
n/a
function getFieldAndForm(formState, modelPath) { var field = (0, _get2.default)(formState, modelPath); var form = formState; (0, _invariant2.default)(form, 'Could not find form for "%s" in the store.', modelPath); if (!field) { var initialValue = (0, _get2.default)(formState.$form.initialValue, modelPath); form = _icepick2.default.merge((0, _formReducer.createInitialState)(formState.$form.model, tempInitialState(modelPath, initialValue )), formState); field = (0, _get2.default)(form, modelPath); } return [field, form]; }
n/a
function updateParentForms(state, localPath, updater) { var parentLocalPath = localPath.slice(0, -1); var value = parentLocalPath.length ? (0, _get2.default)(state, parentLocalPath) : state; if (!value) return state; var form = value.$form; var updatedValue = typeof updater === 'function' ? updater(value) : updater; // const updatedForm = updateFieldState(form, updatedValue); var newState = (0, _assocIn2.default)(state, [].concat(_toConsumableArray(parentLocalPath), ['$form']), _icepick2.default.merge (form, updatedValue)); if (!parentLocalPath.length) return newState; return updateParentForms(newState, parentLocalPath, updater); }
n/a
function updateSubFields(state, localPath, newState) { var field = (0, _get2.default)(state, localPath); // only forms can have fields - // skip if field is not a form if (!field || !field.$form) return state; // intermediate value - not mutated outside function var updatedField = {}; Object.keys(field).forEach(function (key) { if (key === '$form') { updatedField.$form = field.$form; } else { updatedField[key] = updateSubField(field[key], newState); } }); if (!localPath.length) return updatedField; return (0, _assocIn2.default)(state, localPath, updatedField); }
n/a