All files / apps/huella-legal/layers/forms/app/composables useFormSubmission.ts

100% Statements 20/20
80% Branches 4/5
100% Functions 7/7
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                          9x         5x   60x 60x   60x 75x   60x   60x 12x 12x     60x       16x 16x   16x   16x 5x     16x     60x    
import type { Challenge } from "../types/Challenge";
import type { FormError, FormErrorWithId, FormInputEvents } from "@nuxt/ui";
import { useErrorSummary } from "./useErrorSummary";
 
interface ErrorTarget {
    setErrors(errors: FormError[]): void;
    getErrors(): FormErrorWithId[];
}
 
interface Options<Request extends Pick<FormRequest, "honeypot">, Issue extends string> {
    status: Readonly<Ref<string>>;
    errors: Readonly<Ref<readonly { name?: string; message: Issue }[]>>;
    send: (request: Request, challenge: Challenge) => Promise<void>;
    message: (issue: Issue) => string;
    label?: (field: string) => string;
}
 
/**
 * Sends a form's fields with its honeypot through the challenge, puts the server's issues on the
 * fields and in the error summary, and validates on every input once the form has been submitted.
 */
export const useFormSubmission = <
    Request extends Pick<FormRequest, "honeypot">,
    Issue extends string,
>(
    form: Readonly<ShallowRef<ErrorTarget | null>>,
    { status, errors, send, message, label = (field) => field }: Options<Request, Issue>,
) => {
    const honeypot = ref<string>("");
    const submitted = ref<boolean>(false);
 
    const submitting = computed<boolean>(() => status.value === "submitting");
    const validateOn = computed<FormInputEvents[]>(() => (submitted.value ? ["input"] : []));
 
    const { errors: summaryErrors, list } = useErrorSummary(label);
 
    const onError = (formErrors: readonly FormErrorWithId[]): void => {
        submitted.value = true;
        list(formErrors);
    };
 
    const submit = async (
        fields: Omit<Request, "honeypot">,
        challenge: Challenge,
    ): Promise<void> => {
        submitted.value = true;
        list([]);
 
        await send({ ...fields, honeypot: honeypot.value } as Request, challenge);
 
        form.value?.setErrors(
            errors.value.map(({ name, message: issue }) => ({ name, message: message(issue) })),
        );
 
        list(form.value?.getErrors() ?? []);
    };
 
    return { honeypot, submitted, submitting, validateOn, summaryErrors, submit, onError };
};