import icache from '@dojo/framework/core/middleware/icache';
import theme from '../middleware/theme';
import { create, tsx } from '@dojo/framework/core/vdom';
import * as css from '../theme/default/form.m.css';
import createFormMiddleware from './middleware';
const form = createFormMiddleware();
function valueEqual(a, b = {}) {
    return (Object.keys(a).length === Object.keys(b).length &&
        Object.keys(a).every((key) => a[key] === b[key]));
}
function isSubmitForm(properties) {
    return properties.onSubmit !== undefined;
}
function isActionForm(properties) {
    return properties.action !== undefined;
}
const factory = create({ form, theme, icache })
    .properties()
    .children();
export default factory(function Form({ properties, children, middleware: { form, theme, icache } }) {
    const themedCss = theme.classes(css);
    const props = properties();
    let formProps = {
        classes: [theme.variant(), themedCss.root],
        name: props.name
    };
    const { initialValue, value, onValue } = props;
    if (isSubmitForm(props)) {
        formProps = Object.assign({}, formProps, { onsubmit: (event) => {
                event.preventDefault();
                form.submit((value) => props.onSubmit(value));
            } });
    }
    else if (isActionForm(props)) {
        const { action, method = 'post' } = props;
        formProps = Object.assign({}, formProps, { action,
            method });
    }
    const [renderer] = children();
    onValue && form.onValue(onValue);
    if (value) {
        form.value(value);
    }
    else if (initialValue !== undefined && !valueEqual(initialValue, icache.get('initial'))) {
        icache.set('initial', initialValue, false);
        form.value(initialValue);
    }
    return tsx("form", Object.assign({}, formProps), renderer(form));
});
const formGroupFactory = create({ theme })
    .properties()
    .children();
export const FormGroup = formGroupFactory(function FormRow({ properties, children, middleware: { theme } }) {
    const { column } = properties();
    const themedCss = theme.classes(css);
    return (tsx("div", { key: "root", classes: [
            theme.variant(),
            themedCss.groupRoot,
            !column && themedCss.row,
            column && themedCss.column
        ] }, children()));
});
const formFieldFactory = create({ theme });
export const FormField = formFieldFactory(function FormField({ children, middleware: { theme } }) {
    const themedCss = theme.classes(css);
    return (tsx("div", { key: "root", classes: [theme.variant(), themedCss.fieldRoot] }, children()));
});

/*# sourceMappingURL=index.mjs.map*/