@nimel/directorr-form
Version:
Form logic in directorr
270 lines (256 loc) • 11 kB
JavaScript
/* (c) Nikita Melnikov - MIT Licensed 2020 - now */
import { makeObservable, observable, computed } from 'mobx';
import { createActionAndEffect, EMPTY_STRING, EMPTY_OBJECT, createPropertyDecoratorFactory, isFunction, callWithPropNotEquallFunc, isLikeAction } from '@nimel/directorr';
export { EMPTY_OBJECT, EMPTY_STRING } from '@nimel/directorr';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
const [actionFormChangeValue, effectFormChangeValue] = createActionAndEffect('FORM.CHANGE_VALUE');
const [actionFormFocus, effectFormFocus] = createActionAndEffect('FORM.FOCUS');
const [actionFormVisit, effectFormVisit] = createActionAndEffect('FORM.VISIT');
const [actionFormChangeStatus, effectFormChangeStatus] = createActionAndEffect('FORM.CHANGE_STATUS');
const [actionFormSubmit, effectFormSubmit] = createActionAndEffect('FORM.SUBMIT');
const [actionFormReset, effectFormReset] = createActionAndEffect('FORM.RESET');
class FormStore {
constructor({ value = EMPTY_STRING, status = 0 /* Status.default */, message, } = EMPTY_OBJECT) {
this.isChanged = false;
this.isVisited = false;
this.isFocused = false;
this.changeValue = (value) => ({ value });
this.toChangeValue = ({ value }) => {
this.isChanged = true;
this.value = value;
};
this.focus = () => {
this.visit();
return { focus: true };
};
this.blur = () => ({ focus: false });
this.toFocus = ({ focus }) => {
this.isFocused = focus;
};
this.visit = () => (this.isVisited ? null : undefined);
this.toVisit = () => {
this.isVisited = true;
};
this.changeStatusToInvalid = (message) => ({ status: 2 /* Status.invalid */, message });
this.changeStatusToValid = () => ({ status: 1 /* Status.valid */ });
this.toChangeStatus = ({ status, message }) => {
this.status = status;
this.message = message;
};
this.submit = () => { };
this.reset = () => { };
this.toReset = () => {
this.value = this.defaultValue;
this.message = this.defaultMessage;
this.status = 0 /* Status.default */;
};
this.defaultValue = value;
this.defaultMessage = message;
this.value = value;
this.status = status;
this.message = message;
makeObservable(this);
}
get isDefault() {
return this.status === 0 /* Status.default */;
}
get isValid() {
return this.status === 1 /* Status.valid */;
}
get isInvalid() {
return this.status === 2 /* Status.invalid */;
}
}
__decorate([
observable,
__metadata("design:type", String)
], FormStore.prototype, "value", void 0);
__decorate([
observable,
__metadata("design:type", String)
], FormStore.prototype, "message", void 0);
__decorate([
observable,
__metadata("design:type", Number)
], FormStore.prototype, "status", void 0);
__decorate([
observable,
__metadata("design:type", Object)
], FormStore.prototype, "isChanged", void 0);
__decorate([
observable,
__metadata("design:type", Object)
], FormStore.prototype, "isVisited", void 0);
__decorate([
observable,
__metadata("design:type", Object)
], FormStore.prototype, "isFocused", void 0);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], FormStore.prototype, "isDefault", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], FormStore.prototype, "isValid", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], FormStore.prototype, "isInvalid", null);
__decorate([
actionFormChangeValue,
__metadata("design:type", Object)
], FormStore.prototype, "changeValue", void 0);
__decorate([
effectFormChangeValue,
__metadata("design:type", Object)
], FormStore.prototype, "toChangeValue", void 0);
__decorate([
actionFormFocus,
__metadata("design:type", Object)
], FormStore.prototype, "focus", void 0);
__decorate([
actionFormFocus,
__metadata("design:type", Object)
], FormStore.prototype, "blur", void 0);
__decorate([
effectFormFocus,
__metadata("design:type", Object)
], FormStore.prototype, "toFocus", void 0);
__decorate([
actionFormVisit,
__metadata("design:type", Object)
], FormStore.prototype, "visit", void 0);
__decorate([
effectFormVisit,
__metadata("design:type", Object)
], FormStore.prototype, "toVisit", void 0);
__decorate([
actionFormChangeStatus,
__metadata("design:type", Object)
], FormStore.prototype, "changeStatusToInvalid", void 0);
__decorate([
actionFormChangeStatus,
__metadata("design:type", Object)
], FormStore.prototype, "changeStatusToValid", void 0);
__decorate([
effectFormChangeStatus,
__metadata("design:type", Object)
], FormStore.prototype, "toChangeStatus", void 0);
__decorate([
actionFormSubmit,
__metadata("design:type", Object)
], FormStore.prototype, "submit", void 0);
__decorate([
actionFormReset,
__metadata("design:type", Object)
], FormStore.prototype, "reset", void 0);
__decorate([
effectFormReset,
__metadata("design:type", Object)
], FormStore.prototype, "toReset", void 0);
const useWithEffects = (moduleName) => `${moduleName}: use only with effect decorator`;
const callWithWrongSchema = (moduleName, schema) => `${moduleName}: call with arg=${schema} not like yup - ObjectSchema`;
const propNotExistInClass = (moduleName, prop, store) => `${moduleName}: formStore in prop=${prop} not exist in class=${store}`;
const propInClassNotLikeFormStore = (moduleName, prop, formStore) => `${moduleName}: formStore in prop=${prop} not like FormStore=${formStore}`;
const DEFAULT_VALIDATE_OPTIONS = {
abortEarly: false,
strict: true,
payloadProp: 'connectStoreProperty',
};
function isLikeYUPSchema(schema) {
return !!schema.fields;
}
function createSchemaContext(moduleName, schema, options = {}) {
if (!isLikeYUPSchema(schema))
throw new TypeError(callWithWrongSchema(moduleName, schema));
return [schema, Object.assign(Object.assign({}, DEFAULT_VALIDATE_OPTIONS), options), Object.keys(schema.fields)];
}
const VALUE_PROP_NAME = 'value';
function isLikeFormStore(store) {
return !!(VALUE_PROP_NAME in store && store.changeStatusToInvalid && store.changeStatusToValid);
}
function calcValues(moduleName, fields, store) {
const result = {};
for (let i = 0, l = fields.length, prop, formStore; i < l; ++i) {
prop = fields[i];
formStore = store[prop];
if (!formStore)
throw new Error(propNotExistInClass(moduleName, prop, store));
if (!isLikeFormStore(formStore))
throw new TypeError(propInClassNotLikeFormStore(moduleName, prop, formStore));
result[prop] = formStore.value || undefined;
}
return result;
}
const MODULE_NAME = 'validate';
function validateSchema(payload, valueFunc, store, [schema, options, fields]) {
if (isLikeAction(payload))
throw new Error(useWithEffects(MODULE_NAME));
let resultPayload = payload || EMPTY_OBJECT;
const payloadProp = resultPayload[options.payloadProp];
if (!payloadProp)
return;
const values = calcValues(MODULE_NAME, fields, store);
try {
schema.validateSyncAt(payloadProp, values, options);
store[payloadProp].changeStatusToValid();
}
catch (validationError) {
store[payloadProp].changeStatusToInvalid(validationError.errors[0]);
resultPayload = Object.assign(Object.assign({}, resultPayload), { validationError });
}
return valueFunc(resultPayload);
}
function initializer(initObject, value, property, ctx, validate = validateSchema) {
if (!isFunction(value))
throw new TypeError(callWithPropNotEquallFunc(MODULE_NAME, property));
return (payload) => validate(payload, value, initObject, ctx);
}
const validate = createPropertyDecoratorFactory(MODULE_NAME, initializer, createSchemaContext);
const MODULE_NAME$1 = 'validateAll';
function validateSchema$1(payload, valueFunc, store, [schema, options, fields]) {
if (isLikeAction(payload))
throw new Error(useWithEffects(MODULE_NAME$1));
let resultPayload = payload || EMPTY_OBJECT;
const values = calcValues(MODULE_NAME$1, fields, store);
try {
schema.validateSync(values, options);
fields.forEach(prop => store[prop].changeStatusToValid());
}
catch (validationError) {
validationError.inner.forEach((e) => store[e.path].changeStatusToInvalid(e.message));
resultPayload = Object.assign(Object.assign({}, resultPayload), { validationError });
}
return valueFunc(resultPayload);
}
function initializer$1(initObject, value, property, ctx, validate = validateSchema$1) {
if (!isFunction(value))
throw new Error(callWithPropNotEquallFunc(MODULE_NAME$1, property));
return (payload) => validate(payload, value, initObject, ctx);
}
const validateAll = createPropertyDecoratorFactory(MODULE_NAME$1, initializer$1, createSchemaContext);
export { FormStore, actionFormChangeStatus, actionFormChangeValue, actionFormFocus, actionFormReset, actionFormSubmit, actionFormVisit, effectFormChangeStatus, effectFormChangeValue, effectFormFocus, effectFormReset, effectFormSubmit, effectFormVisit, validate, validateAll };