import React, { useRef, useEffect, useState } from 'react'; import { classNames } from 'primereact/utils'; import { __ } from '@wordpress/i18n'; import { head } from 'ramda'; // components import { InputText } from 'primereact/inputtext'; import { Button } from 'primereact/button'; import { Menu } from 'primereact/menu'; import { Dropdown } from 'primereact/dropdown'; import { InputNumber } from 'primereact/inputnumber'; const FormFieldRepeaterCriteria = ({ data, setDataFn, fieldName, options = [], errors, register, label, infoText, config = {} }) => { const forMenu = useRef(null); const [stateFieldData, setStateFieldData] = useState([]); const [threshold, setThreshold] = useState(0); const menuItems = [ { type: 'existing', label: __('Esistente', 'gepafin'), command: (data) => { setStateFieldData([...stateFieldData, { id: null, value: '', status: data.item.type }]); } }, { type: 'new', label: __('Nuovo', 'gepafin'), command: (data) => { setStateFieldData([...stateFieldData, { id: null, value: '', status: data.item.type }]); } } ] const removeItem = (index) => { const newData = stateFieldData.toSpliced(index, 1); setStateFieldData(newData); } const selectItem = (e, index) => { const targetedOption = head(options.filter(o => o.value === e.value)); if (targetedOption) { const newData = stateFieldData.map((o, i) => { if (i === index) { o.value = targetedOption.value; o.score = targetedOption.score; o.id = targetedOption.id; } return o; }); console.log('newData', newData) setStateFieldData(newData); } } const onInputChange = (value, index, name) => { const newData = stateFieldData.map((o, i) => { if (i === index) { o[name] = value; } return o; }) setStateFieldData(newData); } const onThresholdChange = (value) => { setThreshold(value); setDataFn('threshold', value, { shouldValidate: true }); } const properField = (item, i) => { return item.status === 'new' ? onInputChange(e.target.value, i, 'value')}/> : selectItem(e, i)} optionDisabled={(opt) => usedExistingValues.includes(opt.value)} options={options} optionLabel="value"/> } const usedExistingValues = stateFieldData .filter(o => o.status === 'existing') .map(o => o.value); useEffect(() => { const storeFieldData = data[fieldName] ?? []; const newData = storeFieldData.map(o => ({ ...o, status: o.id ? 'existing' : 'new' })); setStateFieldData(newData); setThreshold(data['threshold']) register(fieldName, config) register('threshold', { required: __('È obbligatorio', 'gepafin') }) }, []) useEffect(() => { setDataFn(fieldName, [...stateFieldData], { shouldValidate: true }); }, [stateFieldData]) return (
onThresholdChange(e.value)}/>
{stateFieldData.map((o, i) =>
{properField(o, i)}
{o.status === 'new' && infoText ? {infoText} : null}
onInputChange(e.value, i, 'score')}/>
)}
) } export default FormFieldRepeaterCriteria;