'use strict';

var tslib_es6 = require('./tslib.es6-cjs.js');
var React = require('react');
var reactHookForm = require('react-hook-form');

const Form = React.forwardRef(function InternalForm({ onSubmit, children, onStateChange }, ref) {
    const methods = reactHookForm.useForm({
        mode: "onTouched",
    });
    const { trigger, handleSubmit, formState: { isDirty, isValid }, } = methods;
    React.useEffect(() => onStateChange && onStateChange({ isDirty, isValid }), [isDirty, isValid]);
    React.useImperativeHandle(ref, () => ({
        /**
         * The `trigger()` method can also accept an array
         * of fields to validate. We may at some point want
         * to consider adding a `validate()` method to the
         * `Form` component.
         */
        submit: () => tslib_es6.__awaiter(this, void 0, void 0, function* () {
            const valid = yield trigger(undefined, { shouldFocus: true });
            if (valid) {
                submitHandler();
            }
        }),
    }));
    /**
     * If an onSubmit is not passed into a form, it will only be used
     * for validation. For that, we do not need to wrap it in a <form>
     * tag. This allows the <Form> component to be used in legacy code.
     */
    const Wrapper = onSubmit ? "form" : "div";
    const formProps = {
        onSubmit: onSubmit && handleSubmit(submitHandler),
    };
    return (React.createElement(reactHookForm.FormProvider, Object.assign({}, methods),
        React.createElement(Wrapper, Object.assign({}, formProps, { "data-testid": "atlantis-form" }), children)));
    function submitHandler() {
        onSubmit && onSubmit();
    }
});

exports.Form = Form;
