UNPKG

@modular-forms/solid

Version:

The modular and type-safe form library for SolidJS

60 lines (59 loc) 2.27 kB
import { batch, createEffect, onCleanup, untrack } from 'solid-js'; import { reset } from '../methods'; import { getUniqueId, updateFormState } from '../utils'; export function createLifecycle({ of: form, name, getStore, validate, validateOn, revalidateOn, transform, keepActive = false, keepState = true, }) { createEffect(() => { // Get store of field or field array const store = getStore(); // Add validation functions store.validate = validate ? Array.isArray(validate) ? validate : [validate] : []; // Set validation mode overrides store.validateOn = validateOn; store.revalidateOn = revalidateOn; // Add transformation functions if ('transform' in store) { store.transform = transform ? Array.isArray(transform) ? transform : [transform] : []; } // Create unique consumer ID const consumer = getUniqueId(); // Add consumer to field store.consumers.add(consumer); // Mark field as active and update form state if necessary if (!untrack(store.active.get)) { batch(() => { store.active.set(true); updateFormState(form); }); } // On cleanup, remove consumer from field onCleanup(() => setTimeout(() => { store.consumers.delete(consumer); // Mark field as inactive if there is no other consumer batch(() => { if (!keepActive && !store.consumers.size) { store.active.set(false); // Reset state if it is not to be kept if (!keepState) { reset(form, name); // Otherwise just update form state } else { updateFormState(form); } } }); // Remove unmounted elements if ('elements' in store) { store.elements.set((elements) => elements.filter((element) => element.isConnected)); } })); }); }