pagamio-frontend-commons-lib
Version:
Pagamio library for Frontend reusable components like the form engine and table container
64 lines (63 loc) • 2.91 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { Controller } from 'react-hook-form';
import { useMemo } from 'react';
import { getInputComponent } from '../registry';
const FieldWrapper = ({ field, control, errors, layout, onFieldUpdate, onFieldChange, pendingUpdatesRef, fieldChangeRef, notifyPendingUpdate, }) => {
const InputComponent = getInputComponent(field.type);
const wrapperClass = useMemo(() => {
if (layout === 'horizontal') {
return 'w-1/2 px-4';
}
return `col-span-${field?.gridSpan ?? '12'}`;
}, [layout, field?.gridSpan]);
if (!InputComponent) {
console.error(`No component registered for type: ${field.type}`);
return null;
}
const handleFieldChange = (value, onChange, onChangeField) => {
// Extract actual value from event if needed
let actualValue = value;
if (value && typeof value === 'object' && value.target !== undefined) {
// This is a SyntheticEvent, extract the value
actualValue = value.target.value;
}
// Call the provided onChange function with the actual value
onChange(actualValue);
// Call any custom onChange handler if provided
if (onChangeField) {
onChangeField(actualValue);
}
// Call the onFieldChange callback if provided
if (onFieldChange) {
onFieldChange(field.name, actualValue);
}
// Only queue field updates if this field has dependencies
if (onFieldUpdate?.[field.name]) {
if (fieldChangeRef && !fieldChangeRef.current.has(field.name)) {
fieldChangeRef.current.add(field.name);
}
// Add the update to the pending queue
if (pendingUpdatesRef) {
pendingUpdatesRef.current.set(field.name, actualValue);
if (notifyPendingUpdate) {
notifyPendingUpdate(); // Notify parent component about update
}
}
}
};
if (field.name === 'email') {
field.validation = {
...field.validation,
pattern: {
value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
message: 'Please enter a valid email address',
},
};
}
// Skip rendering if field is hidden
if (field.isHidden) {
return null;
}
return (_jsx("div", { className: `${wrapperClass} mb-2`, children: _jsx(Controller, { name: field.name, control: control, rules: field.validation, render: ({ field: inputProps }) => (_jsx("div", { className: "flex flex-col", children: _jsx(InputComponent, { ...inputProps, field: field, error: errors[field.name], onChange: (value) => handleFieldChange(value, inputProps.onChange, field?.onChange), options: field.options ?? [] }) })) }) }));
};
export default FieldWrapper;