UNPKG

vcc-ui

Version:

A React library for building user interfaces at Volvo Cars

83 lines (80 loc) 2.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useForm = useForm; exports.useFormDebugger = useFormDebugger; var _fastLoops = require("fast-loops"); function useForm() { for (var _len = arguments.length, fields = new Array(_len), _key = 0; _key < _len; _key++) { fields[_key] = arguments[_key]; } function touchFields() { fields.forEach(field => field.touch()); } function reset() { fields.forEach(field => field.update(field.initial)); } function submit(onSubmit) { const isValid = (0, _fastLoops.arrayReduce)(fields, (isValid, field) => isValid && field.isValid, true); const data = (0, _fastLoops.arrayReduce)(fields, (data, _ref) => { let { value, name } = _ref; data[name] = value; return data; }, {}); // if the form is invalid, we touch all fields to reveal the error messages if (!isValid) { touchFields(); } onSubmit(isValid, data); } return { touchFields, submit, reset }; } // TODO: make this only available in development // for now we're fine due to code splitting though function useFormDebugger() { for (var _len2 = arguments.length, fields = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { fields[_key2] = arguments[_key2]; } const isValid = (0, _fastLoops.arrayReduce)(fields, (isValid, field) => isValid && field.isValid, true); const data = (0, _fastLoops.arrayReduce)(fields, (data, _ref2) => { let { name, value } = _ref2; data[name] = value; return data; }, {}); const fieldData = (0, _fastLoops.arrayReduce)(fields, (data, _ref3) => { let { name, value, isValid, isTouched, isDisabled, isLoading, errorMessage } = _ref3; data[name] = { value, isTouched, isValid, isDisabled, isLoading, errorMessage }; return data; }, {}); return { data, fields: fieldData, isValid }; }