@modular-forms/qwik
Version:
The modular and type-safe form library for Qwik
77 lines (76 loc) • 3.38 kB
JavaScript
import { jsx as _jsx } from "@builder.io/qwik/jsx-runtime";
import { FormError } from '../exceptions';
import { getValues, setResponse, validate } from '../methods';
import { setErrorResponse, setFieldErrors } from '../utils';
/**
* Form element that takes care of validation and simplifies submission.
*/
export function Form({ of: form, action, onSubmit$, responseDuration: duration, keepResponse, shouldActive, shouldTouched, shouldDirty, shouldFocus, reloadDocument, children, ...formProps }) {
// Destructure form props
const { encType } = formProps;
// Create options object
const options = {
duration,
shouldActive,
shouldTouched,
shouldDirty,
shouldFocus,
};
return (_jsx("form", { noValidate: true, ...formProps, method: "post", action: action?.actionPath, "preventdefault:submit": !reloadDocument, ref: (element) => {
form.element = element;
}, "onSubmit$": async (event, element) => {
// Reset response if it is not to be kept
if (!keepResponse) {
form.response = {};
}
// Increase submit count and set submitted and submitting to "true"
form.submitCount++;
form.submitted = true;
form.submitting = true;
// Try to run submit actions if form is valid
try {
if (await validate(form, options)) {
// Get current values of form
const values = getValues(form, options);
// Run submit actions of form
const [actionResult] = await Promise.all([
!reloadDocument
? action?.submit(encType ? new FormData(element) : values)
: undefined,
// eslint-disable-next-line qwik/valid-lexical-scope
onSubmit$?.(values, event),
]);
// Set form action result if necessary
if (actionResult?.value) {
const { errors, response } = actionResult.value;
setFieldErrors(form, errors, { ...options, shouldFocus: false });
if (Object.keys(response).length) {
setResponse(form, response, options);
}
else {
setErrorResponse(form, errors, options);
}
}
}
// If an error occurred, set error to fields and response
}
catch (error) {
if (error instanceof FormError) {
setFieldErrors(form, error.errors, {
...options,
shouldFocus: false,
});
}
if (!(error instanceof FormError) || error.message) {
setResponse(form, {
status: 'error',
message: error?.message || 'An unknown error has occurred.',
}, options);
}
// Finally set submitting back to "false"
}
finally {
form.submitting = false;
}
}, children: children }));
}