import { FormGroupApi } from '@tanstack/form-core';
import { createComponent, createComputed, createSignal, onCleanup, onMount, } from 'solid-js';
import { useStore } from '@tanstack/solid-store';
// ugly way to trick solid into triggering updates for changes on the formGroupApi
function makeFormGroupReactive(formGroupApi) {
    const [group, setGroup] = createSignal(formGroupApi, { equals: false });
    // Handle shallow comparison to make sure that Derived doesn't create a new setGroup call every time
    const store = useStore(formGroupApi.store, (store) => store);
    // Run before initial render
    createComputed(() => {
        // Use the store to track dependencies
        store();
        setGroup(formGroupApi);
    });
    return group;
}
export function createFormGroup(opts) {
    const options = opts();
    const api = new FormGroupApi(options);
    let mounted = false;
    // Instantiates form group meta and removes it when unrendered
    onMount(() => {
        const cleanupFn = api.mount();
        mounted = true;
        onCleanup(() => {
            cleanupFn();
            mounted = false;
        });
    });
    /**
     * formGroupApi.update should not have any side effects. Think of it like a `useRef`
     * that we need to keep updated every render with the most up-to-date information.
     *
     * createComputed to make sure this effect runs before render effects
     */
    createComputed(() => {
        if (!mounted)
            return;
        api.update(opts());
    });
    return makeFormGroupReactive(api);
}
export function FormGroup(props) {
    const formGroupApi = createFormGroup(() => {
        const { children, ...formGroupOptions } = props;
        return formGroupOptions;
    });
    return <>{createComponent(() => props.children(formGroupApi), {})}</>;
}
//# sourceMappingURL=createFormGroup.jsx.map