@modular-forms/qwik
Version:
The modular and type-safe form library for Qwik
60 lines (59 loc) • 2.64 kB
JavaScript
import { jsx as _jsx } from "@builder.io/qwik/jsx-runtime";
import { component$, Slot, useVisibleTask$, } from '@builder.io/qwik';
import { reset } from '../methods';
import { getUniqueId, updateFormState } from '../utils';
export function Lifecycle(props, key, flags) {
return component$(({ of: form, store, validate, validateOn, revalidateOn, transform, keepActive = false, keepState = true, }) => {
// TODO: Switch back to `useTask$` once issue #3193 is fixed
// eslint-disable-next-line qwik/no-use-visible-task
useVisibleTask$(({ cleanup }) => {
// Add validation functions
store.internal.validate = validate
? Array.isArray(validate)
? validate
: [validate]
: [];
// Set validation mode overrides
store.internal.validateOn = validateOn;
store.internal.revalidateOn = revalidateOn;
// Add transformation functions
if ('value' in store) {
store.internal.transform = transform
? Array.isArray(transform)
? transform
: [transform]
: [];
}
// Create unique consumer ID
const consumer = getUniqueId();
// Add consumer to field
store.internal.consumers.push(consumer);
// Mark field as active and update form state if necessary
if (!store.active) {
store.active = true;
updateFormState(form);
}
// On cleanup, remove consumer from field
cleanup(() => setTimeout(() => {
store.internal.consumers.splice(store.internal.consumers.indexOf(consumer), 1);
// Mark field as inactive if there is no other consumer
if (!keepActive && !store.internal.consumers.length) {
store.active = false;
// Reset state if it is not to be kept
if (!keepState) {
reset(form, store.name);
// Otherwise just update form state
}
else {
updateFormState(form);
}
}
// Remove unmounted elements
if ('value' in store) {
store.internal.elements = store.internal.elements.filter((element) => element.isConnected);
}
}, 15));
});
return _jsx(Slot, {});
})(props, key, flags);
}