"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FormField = FormField;
exports.createFieldValidator = createFieldValidator;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _eui = require("@elastic/eui");
var _formik = require("formik");
var _react = _interopRequireDefault(require("react"));
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
/**
* Polymorphic component that renders a form field with all state required for inline validation.
*
* @example Text field with validation rule:
* ```typescript
*
*
*
* ```
*
* @example Color picker using non-standard value prop and change handler:
* ```typescript
*
* formik.setFieldValue('color', value)}
* />
*
* ```
*
* @throws Error if not a child of a `` component.
*/
function FormField({
as,
validate,
onBlur,
...rest
}) {
const Component = as || _eui.EuiFieldText;
const [field, meta, helpers] = (0, _formik.useField)({
name: rest.name,
validate: typeof validate === 'object' ? createFieldValidator(validate) : validate
});
return /*#__PURE__*/_react.default.createElement(Component, (0, _extends2.default)({
isInvalid: meta.touched && !!meta.error
}, field, rest, {
onBlur: event => {
helpers.setTouched(true); // Marking as touched manually here since some EUI components don't pass on the native blur event which is required by `field.onBlur()`.
onBlur === null || onBlur === void 0 ? void 0 : onBlur(event);
}
}));
}
function createFieldValidator(options) {
return value => {
if (options.required && typeof value !== 'number' && !value) {
return options.required;
}
if (options.pattern && !options.pattern.value.test(value)) {
return options.pattern.message;
}
if (options.minLength && (!value || (typeof value === 'object' || typeof value === 'string') && value.length < options.minLength.value)) {
return options.minLength.message;
}
if (options.maxLength && value && (typeof value === 'object' || typeof value === 'string') && value.length > options.maxLength.value) {
return options.maxLength.message;
}
if (options.min && (isNaN(value) || value < options.min.value)) {
return options.min.message;
}
if (options.max && (isNaN(value) || value > options.max.value)) {
return options.max.message;
}
};
}