All files / src/components/form/XForm XForm.tsx

0% Statements 0/23
0% Branches 0/39
0% Functions 0/14
0% Lines 0/22

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                                                                                                                                                                                                                                                                                                                                                                                                                           
import React, { useState } from "react";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
} from "@/components/ui/form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { FieldErrors, useForm } from "react-hook-form";
import { Checkbox } from "@/components/ui/checkbox";
import { XField, XFormField } from "../XField/XField";
import { ChevronLeft } from "lucide-react";
import { ChevronRight } from "lucide-react";
import NewlineText from "@/components/text/NewlineText/NewlineText";
 
export interface XFormInterface {
  title: string;
  formSchema: z.ZodObject<any>;
  fields: XFormField[];
  values?: Record<string, unknown>;
  onSubmit: (values: object) => void;
  goBack?: () => void;
  goForward?: () => void;
}
 
export const XForm: React.FC<XFormInterface> = (props: XFormInterface) => {
  const [errMessages, setErrMessages] = useState<string[] | null>(null);
  const [nonFieldsChecked, setNonFieldsChecked] = useState<
    Record<string, boolean>
  >(
    props.fields
      .filter((item) => {
        return item.is_field === false;
      })
      .reduce((acc, ffield) => {
        acc[ffield.name] = false;
        return acc;
      }, {} as Record<string, boolean>)
  );
  const form = useForm<z.infer<typeof props.formSchema>>({
    resolver: zodResolver(props.formSchema),
    defaultValues: {
      ...props.values,
    },
  });
 
  function onSubmit(data: Record<string, unknown>) {
    props.onSubmit(data);
    setErrMessages(null);
    if (props.goForward !== undefined) {
      props.goForward();
    }
  }
 
  function onError(errors: FieldErrors) {
    const errorMessages = Object.entries(errors).map(
      ([fname, error]) => `Field '${fname}' - ${error?.message as string}`
    );
    setErrMessages(errorMessages);
  }
 
  return (
    <Form {...form}>
      <form
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        onSubmit={form.handleSubmit(onSubmit, onError)}
        className="flex flex-col gap-8 bg-slate-100 p-10 rounded-lg form shadow-xl"
      >
        {props.fields.map((form_field, idx) => {
          return (
            <>
              {(form_field.is_field ?? true) && (
                <FormField
                  key={idx}
                  control={form.control}
                  name={form_field.name}
                  defaultValue={(props.values ?? {})[form_field.name]}
                  render={({ field }) => (
                    <XField
                      field={field}
                      form={form}
                      form_field={form_field}
                      value={(props.values ?? {})[form_field.name] as string}
                    />
                  )}
                />
              )}
              {form_field.is_field === false && (
                <>
                  <FormItem key={idx}>
                    <FormLabel>{form_field.title}</FormLabel>
                    <FormControl>
                      <Checkbox
                        className="bg-white"
                        defaultChecked={
                          (form_field.input_conditional_children ?? []).filter(
                            (child) => {
                              return (
                                (props.values ?? {})[child.name] !== undefined
                              );
                            }
                          ).length > 0 ||
                          nonFieldsChecked[form_field.name] ||
                          (props.values ?? {})[form_field.name] !== undefined
                        }
                        checked={
                          nonFieldsChecked[form_field.name] ||
                          (form_field.input_conditional_children ?? []).filter(
                            (child) => {
                              return (
                                (props.values ?? {})[child.name] !== undefined
                              );
                            }
                          ).length > 0
                        }
                        onCheckedChange={(checked) => {
                          setNonFieldsChecked((prev) => ({
                            ...prev,
                            [form_field.name]: !!checked, // or Boolean(checked)
                          }));
                        }}
                      />
                    </FormControl>
                    <FormDescription>{form_field.description}</FormDescription>
                  </FormItem>
                  {(nonFieldsChecked[form_field.name] ||
                    (form_field.input_conditional_children ?? []).filter(
                      (child) => {
                        return (props.values ?? {})[child.name] !== undefined;
                      }
                    ).length > 0) && (
                    <div className="border border-gray-600 bg-slate-200 rounded-lg p-4 flex flex-col gap-8">
                      {form_field.input_conditional_children?.map(
                        (child, idx2) => {
                          return (
                            <FormField
                              key={idx2}
                              control={form.control}
                              name={child.name}
                              defaultValue={(props.values ?? {})[child.name]}
                              render={({ field }) => (
                                <XField
                                  key={idx2}
                                  field={field}
                                  form={form}
                                  form_field={child}
                                  value={
                                    (props.values ?? {})[child.name] as string
                                  }
                                />
                              )}
                            />
                          );
                        }
                      )}
                    </div>
                  )}
                </>
              )}
            </>
          );
        })}
        {errMessages !== null && (
          <div className="text-white border bg-red-400 p-4 rounded-lg">
            <span className="font-bold">There are errors in the form:</span>
            <br></br>
            <NewlineText lines={errMessages} />
          </div>
        )}
        <div className="flex flex-row justify-between">
          {props.goBack !== undefined ? (
            <button
              onClick={() => (props.goBack ? props.goBack() : {})}
              className="bg-slate-100 disabled:bg-gray-600 disabled:text-white disabled:pointer-events-none"
            >
              <ChevronLeft /> Back{" "}
            </button>
          ) : (
            <span />
          )}
          <button
            type="submit"
            className={`${
              props.goForward !== undefined
                ? "bg-slate-200"
                : "bg-black text-white"
            } justify-right disabled:bg-gray-600 disabled:text-white disabled:pointer-events-none`}
          >
            {props.goForward !== undefined ? (
              <>
                Next
                <ChevronRight />
              </>
            ) : (
              "Submit"
            )}
          </button>
        </div>
      </form>
    </Form>
  );
};