import FieldProperties from "../components/forms/fields/field_properties"; import Token from "./token"; export interface FormError { field_name: string; message: string; } export function deleteEmptyFields(form: FormData) { const trimmed_form = new FormData(); for(const key of form.keys()) { if(form.get(key) != '') trimmed_form.append(key, form.get(key)); } return trimmed_form; } export function setFormErrorsInSessionStorage(errors: Array) { for(const [key, value] of Object.entries(errors)) { sessionStorage.setItem(key, value); } } export function setFieldErrorMessages(fields: FieldProperties[], errors: FormError[]) { for(const field of fields) { const error = errors.find(e => e.field_name == field.name) if(error){ field.error_message = error.message; } } return fields; } export function clearSessionStorage() { const token = new Token(); const stored_token = sessionStorage.getItem('token'); const refresh_token = sessionStorage.getItem('refresh'); sessionStorage.clear(); if(stored_token && refresh_token) { token.set(stored_token); token.setRefresh(refresh_token); } } export function formHasErrors(fields: Array) { for(const field_key of fields) { if(sessionStorage.getItem(field_key)) return true; } return false; } export function renderErrors(errors: Array) { for(const error of errors) { const field_div = document.getElementById(error.field_div_id); const input_label = field_div?.querySelector("label"); const input_field = field_div?.querySelector("input"); input_label?.classList.add("text-red-700"); input_field?.classList.add("bg-red-50 border border-red-500 text-red-900 placeholder-red-700 focus:ring-red-500 dark:bg-gray-700 focus:border-red-500"); } }