@woocommerce/components
Version:
UI components for WooCommerce.
51 lines (50 loc) • 2.49 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicForm = void 0;
/**
* External dependencies
*/
const element_1 = require("@wordpress/element");
const components_1 = require("@wordpress/components");
const i18n_1 = require("@wordpress/i18n");
/**
* Internal dependencies
*/
const index_1 = require("../index");
const field_types_1 = require("./field-types");
const fieldTypeMap = {
text: field_types_1.TextField,
password: field_types_1.PasswordField,
checkbox: field_types_1.CheckboxField,
select: field_types_1.SelectField,
default: field_types_1.TextField,
};
const getInitialConfigValues = (fields) => fields.reduce((data, field) => ({
...data,
[field.id]: field.type === 'checkbox' ? field.value === 'yes' : field.value,
}), {});
const DynamicForm = ({ fields: baseFields = [], isBusy = false, onSubmit = () => { }, onChange = () => { }, validate = () => ({}), submitLabel = (0, i18n_1.__)('Proceed', 'woocommerce'), }) => {
// Support accepting fields in the format provided by the API (object), but transform to Array
const fields = baseFields instanceof Array ? baseFields : Object.values(baseFields);
const initialValues = (0, element_1.useMemo)(() => getInitialConfigValues(fields), [fields]);
return (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(0, element_1.createElement)(index_1.Form, { initialValues: initialValues, onChange: onChange, onSubmit: onSubmit, validate: validate }, ({ getInputProps, handleSubmit, }) => {
return ((0, element_1.createElement)("div", { className: "woocommerce-component_dynamic-form" },
fields.map((field) => {
if (field.type &&
!(field.type in fieldTypeMap)) {
/* eslint-disable no-console */
console.warn(`Field type of ${field.type} not current supported in DynamicForm component`);
/* eslint-enable no-console */
return null;
}
const Control = fieldTypeMap[field.type || 'default'];
return ((0, element_1.createElement)(Control, { key: field.id, field: field, ...getInputProps(field.id) }));
}),
(0, element_1.createElement)(components_1.Button, { isPrimary: true, isBusy: isBusy, onClick: () => {
handleSubmit();
} }, submitLabel)));
}));
};
exports.DynamicForm = DynamicForm;