UNPKG

@data-driven-forms/react-form-renderer

Version:

React Form Renderer. Data Driven Forms converts JSON form definitions into fully functional React forms.

257 lines 15.7 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var react_final_form_1 = require("react-final-form"); var enhanced_on_change_1 = __importDefault(require("./enhanced-on-change")); var renderer_context_1 = __importDefault(require("../renderer-context")); var convert_initial_value_1 = __importDefault(require("./convert-initial-value")); var assign_special_type_1 = __importDefault(require("./assign-special-type")); var component_types_1 = __importDefault(require("../component-types")); var validator_helpers_1 = require("./validator-helpers"); var compose_validators_1 = __importDefault(require("../compose-validators")); var isEqual_1 = __importDefault(require("lodash/isEqual")); var get_1 = __importDefault(require("lodash/get")); var calculateInitialValue = function (props) { if (Object.prototype.hasOwnProperty.call(props, 'initialValue') && props.dataType) { return (0, convert_initial_value_1.default)(props.initialValue, props.dataType); } }; var calculateArrayValidator = function (props, validate, component, validatorMapper) { if ((validate || props.dataType) && component_types_1.default.FIELD_ARRAY === component) { return (0, validator_helpers_1.prepareArrayValidator)((0, validator_helpers_1.getValidate)(validate, props.dataType, validatorMapper)); } }; var calculateValidate = function (props, validate, component, validatorMapper, setWarning, useWarnings) { if ((validate || props.dataType) && component_types_1.default.FIELD_ARRAY !== component) { var validateFn_1 = (0, compose_validators_1.default)((0, validator_helpers_1.getValidate)(validate, props.dataType, validatorMapper)); if (useWarnings) { return function (value, allValues, meta) { return __awaiter(void 0, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: setWarning === null || setWarning === void 0 ? void 0 : setWarning(undefined); return [4 /*yield*/, validateFn_1(value, allValues, meta)]; case 1: result = _a.sent(); if ((result === null || result === void 0 ? void 0 : result.type) === 'warning') { setWarning === null || setWarning === void 0 ? void 0 : setWarning(result.error); return [2 /*return*/]; } return [2 /*return*/, result]; } }); }); }; } return validateFn_1; } }; var init = function (_a) { var props = _a.props, validate = _a.validate, component = _a.component, validatorMapper = _a.validatorMapper, setWarning = _a.setWarning, useWarnings = _a.useWarnings; return ({ initialValue: calculateInitialValue(props), arrayValidator: calculateArrayValidator(props, validate, component, validatorMapper), validate: calculateValidate(props, validate, component, validatorMapper, setWarning, useWarnings), type: (0, assign_special_type_1.default)(component), }); }; var reducer = function (state, action) { switch (action.type) { case 'setType': return __assign(__assign({}, state), { type: action.specialType }); case 'setValidators': return __assign(__assign({}, state), { validate: action.validate, arrayValidator: action.arrayValidator }); case 'setInitialValue': return __assign(__assign({}, state), { initialValue: action.initialValue }); default: return state; } }; var createFieldProps = function (name, formOptions) { var _a = formOptions.getFieldState(name) || {}, value = _a.value, blur = _a.blur, change = _a.change, focus = _a.focus, meta = __rest(_a, ["value", "blur", "change", "focus"]); return { meta: meta, input: { name: name, value: value }, }; }; var useFieldApi = function (_a) { var name = _a.name, resolveProps = _a.resolveProps, _b = _a.skipRegistration, skipRegistration = _b === void 0 ? false : _b, props = __rest(_a, ["name", "resolveProps", "skipRegistration"]); var _c = (0, react_1.useContext)(renderer_context_1.default), validatorMapper = _c.validatorMapper, formOptions = _c.formOptions; var _d = (0, react_1.useState)(), warning = _d[0], setWarning = _d[1]; // if there is field initial value, we have to check form initialValues // initialValues should have higher priority var formInitialValue = Object.prototype.hasOwnProperty.call(props, 'initialValue') ? (0, get_1.default)(formOptions.initialValues, name) : undefined; var resolvedProps = resolveProps ? resolveProps(props, createFieldProps(name, formOptions), formOptions) || {} : {}; var combinedProps = __assign(__assign({}, props), resolvedProps); var initializeOnMount = combinedProps.initializeOnMount, component = combinedProps.component, render = combinedProps.render, validate = combinedProps.validate, useWarnings = combinedProps.useWarnings, clearOnUnmount = combinedProps.clearOnUnmount, dataType = combinedProps.dataType, FieldProps = combinedProps.FieldProps, rest = __rest(combinedProps, ["initializeOnMount", "component", "render", "validate", "useWarnings", "clearOnUnmount", "dataType", "FieldProps"]); var _e = (0, react_1.useReducer)(reducer, { props: combinedProps, validate: validate, component: component, validatorMapper: validatorMapper, setWarning: setWarning, useWarnings: useWarnings }, init), _f = _e[0], type = _f.type, initialValue = _f.initialValue, stateValidate = _f.validate, arrayValidator = _f.arrayValidator, dispatch = _e[1]; var mounted = (0, react_1.useRef)(false); var enhancedProps = __assign(__assign(__assign(__assign(__assign(__assign({ dataType: dataType, type: combinedProps.type }, (Object.prototype.hasOwnProperty.call(combinedProps, 'initialValue') ? { initialValue: combinedProps.initialValue } : {})), (Object.prototype.hasOwnProperty.call(combinedProps, 'value') ? { value: combinedProps.value } : {})), FieldProps), (type ? { type: type } : {})), (initialValue ? { initialValue: initialValue } : {})), (stateValidate ? { validate: stateValidate } : {})); var field = (0, react_final_form_1.useField)(name, __assign(__assign({}, enhancedProps), (typeof formInitialValue !== 'undefined' && { initialValue: formInitialValue }))); /** Reinitilize type */ (0, react_1.useEffect)(function () { if (mounted.current) { var specialType = (0, assign_special_type_1.default)(component); if (specialType !== type) { dispatch({ type: 'setType', specialType: specialType }); } } }, [component]); /** Reinitilize array validator/validate */ (0, react_1.useEffect)(function () { if (mounted.current) { dispatch({ type: 'setValidators', validate: calculateValidate(enhancedProps, validate, component, validatorMapper, setWarning, useWarnings), arrayValidator: calculateArrayValidator(enhancedProps, validate, component, validatorMapper), }); } /** * We have to stringify the validate array in order to preven infinite looping when validate was passed directly to useFieldApi * const x = useFieldApu({name: 'foo', validate: [{type: 'bar'}]}) will trigger infinite looping witouth the serialize. * Using stringify is acceptable here since the array is usually very small. * If we notice performance hit, we can implement custom hook with a deep equal functionality. */ }, [validate ? JSON.stringify(validate) : false, component, dataType]); /** Re-convert initialValue when changed */ (0, react_1.useEffect)(function () { if (mounted.current) { var newInitialValue = calculateInitialValue(enhancedProps); if (!(0, isEqual_1.default)(initialValue, newInitialValue)) { dispatch({ type: 'setInitialValue', initialValue: newInitialValue, }); } } }, [enhancedProps.initialValue, dataType]); (0, react_1.useEffect)(function () { var _a; /** * Re initialize field when mounted to the Form * This affects conditional fields */ if (initializeOnMount) { var value = Object.prototype.hasOwnProperty.call(enhancedProps, 'initialValue') ? enhancedProps.initialValue : (_a = formOptions === null || formOptions === void 0 ? void 0 : formOptions.getFieldState(name)) === null || _a === void 0 ? void 0 : _a.initial; field.input.onChange(value); } }, [initializeOnMount, enhancedProps.initialValue, field.meta.initial, dataType]); /** * Prepare deleted value of field */ var fieldClearedValue = Object.prototype.hasOwnProperty.call(rest, 'clearedValue') ? rest.clearedValue : formOptions.clearedValue; (0, react_1.useEffect)(function () { if (!skipRegistration && formOptions.internalRegisterField) { formOptions.internalRegisterField(name); } mounted.current = true; if (field.input.type === 'file' && formOptions.registerInputFile) { formOptions.registerInputFile(field.input.name); } return function () { var _a, _b, _c, _d; mounted.current = false; /** * Delete the value from form state when field is inmounted */ if (clearOnUnmount && clearOnUnmount !== false) { (_b = (_a = field.input) === null || _a === void 0 ? void 0 : _a.onChange) === null || _b === void 0 ? void 0 : _b.call(_a, fieldClearedValue); } if (((_c = field === null || field === void 0 ? void 0 : field.input) === null || _c === void 0 ? void 0 : _c.type) === 'file') { (_d = formOptions === null || formOptions === void 0 ? void 0 : formOptions.unRegisterInputFile) === null || _d === void 0 ? void 0 : _d.call(formOptions, field.input.name); } if (!skipRegistration) { formOptions === null || formOptions === void 0 ? void 0 : formOptions.internalUnRegisterField(name); } }; }, // eslint-disable-next-line react-hooks/exhaustive-deps []); var _initialValue = rest.initialValue, clearedValue = rest.clearedValue, cleanProps = __rest(rest, ["initialValue", "clearedValue"]); /** * construct component props necessary that would live in field provider */ return __assign(__assign(__assign(__assign(__assign({}, cleanProps), field), (arrayValidator && { arrayValidator: arrayValidator })), (useWarnings && { meta: __assign(__assign({}, field.meta), { warning: warning }), })), { input: __assign(__assign({}, field.input), { value: field.input.type === 'file' && typeof field.input.value === 'object' ? field.input.value.inputValue : field.input.value, onChange: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } enhanced_on_change_1.default.apply(void 0, __spreadArray([__assign(__assign({}, field.meta), { dataType: dataType, onChange: field.input.onChange, clearedValue: fieldClearedValue }), args[0]], args.slice(1), false)); } }) }); }; exports.default = useFieldApi; //# sourceMappingURL=use-field-api.js.map