@pagamio/frontend-commons-lib
Version:
Pagamio library for Frontend reusable components like the form engine and table container
53 lines (52 loc) • 2.29 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { detectErrorType } from '../utils/errorDetection';
/**
* Common password validation for authentication forms
*/
export const passwordValidation = {
required: 'Password is required',
min: { value: 8, message: 'Password must be at least 8 characters' },
validate: (value) => /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value) ||
'Password must contain at least one uppercase letter, one lowercase letter, and one number',
};
/**
* Renders a back to login button
*/
export const BackToLoginButton = ({ onBackToLogin, label }) => (_jsx("div", { className: "flex items-center justify-center mt-4", children: _jsx("button", { type: "button", onClick: onBackToLogin, className: "text-right text-sm text-primary-500 hover:underline dark:text-primary-500", children: label }) }));
/**
* Creates a standardized form submission handler
* @param config Form submission configuration
* @param submitAction The action to perform during form submission
* @param successMessage Message to display on success
* @param fallbackErrorMessage Optional fallback error message to display on failure
* @returns A form submission handler function
*/
export const createFormSubmissionHandler = (config, submitAction, successMessage, fallbackErrorMessage = 'Operation failed') => {
const { setIsLoading, setError, addToast, formRef, onSuccess, onError } = config;
return async (data) => {
setIsLoading(true);
setError?.(null);
try {
const response = await submitAction(data);
addToast({ message: successMessage, variant: 'success' });
// Reset form using the form ref
if (formRef.current) {
formRef.current.reset();
}
onSuccess?.(response);
}
catch (error) {
const errorInfo = detectErrorType(error);
const errorMessage = errorInfo.message || fallbackErrorMessage;
setError?.(errorMessage);
addToast({
message: errorMessage,
variant: 'error',
});
onError?.(error instanceof Error ? error : new Error(errorMessage));
}
finally {
setIsLoading(false);
}
};
};