UNPKG

react-tiniest-form

Version:
88 lines (87 loc) 3.05 kB
import { invariantOf } from '../@common/invariantOf'; const createFormsStore = (options) => { const store = {}; const errors = {}; const initStore = (defaultValues) => { defaultValues && Object.entries(invariantOf(defaultValues)).forEach(([name, value]) => { Object.assign(store, { [name]: getInitialFieldInfo(value), }); }); }; const registerField = (name, options) => { store[name] = Object.assign(Object.assign(Object.assign({}, store[name]), options), { value: parseToInputValue(options === null || options === void 0 ? void 0 : options.value), registered: true }); }; const updateFieldValue = (name, options) => { store[name] = Object.assign(Object.assign({}, store[name]), options); }; const getFieldInfo = (name) => { return store[name] ? store[name] : undefined; }; const getFieldValue = (name) => { var _a; return parseToInputValue((_a = store[name]) === null || _a === void 0 ? void 0 : _a.value); }; const watchField = (name) => { store[name] && (store[name].watching = true); }; const isWatching = (name) => { return store[name] && store[name].watching; }; const setError = (name, validation) => { errors[name] = Object.assign({}, validation); }; const deleteError = (name) => { delete errors[name]; }; const validateField = (payload) => { const { name, onInvalid, onValid } = payload; const { value } = store[name]; const { validations } = store[name]; const isAllValid = validations === null || validations === void 0 ? void 0 : validations.every(info => { const { type = '', message = '', validator } = info; const isValid = validator(value); if (!isValid) { store[name].isValid = false; setError(name, { type, message }); onInvalid === null || onInvalid === void 0 ? void 0 : onInvalid({ type, message, validator }); } return isValid; }); if (isAllValid) { store[name].isValid = true; deleteError(name); onValid === null || onValid === void 0 ? void 0 : onValid(); } return isAllValid; }; initStore(options === null || options === void 0 ? void 0 : options.defaultValues); return { store, errors, registerField, updateFieldValue, validateField, getFieldValue, watchField, isWatching, getFieldInfo, }; }; const parseToInputValue = (value) => { if (!value) return ''; if (Array.isArray(value)) return value.join(); return String(value); }; const getInitialFieldInfo = (value) => ({ value: parseToInputValue(value), watching: false, registered: false, isValid: false, validations: [], ref: null, }); export { createFormsStore, parseToInputValue };