ActionFieldsMap.js
2 years ago
DynamicPropertySelect.js
2 years ago
WrapperRequiredControl.js
2 years ago
DynamicPropertySelect.js
92 lines
| 1 | import CurrentActionEditContext |
| 2 | from '../../actions/context/CurrentActionEditContext'; |
| 3 | import ActionFieldsMapContext from '../context/ActionFieldsMapContext'; |
| 4 | import CurrentPropertyMapContext from '../context/CurrentPropertyMapContext'; |
| 5 | |
| 6 | const { |
| 7 | useState, |
| 8 | useContext, |
| 9 | } = wp.element; |
| 10 | |
| 11 | const { |
| 12 | SelectControl, |
| 13 | } = wp.components; |
| 14 | |
| 15 | function DynamicPropertySelect( { |
| 16 | dynamic = [], |
| 17 | parseValue = null, |
| 18 | children = null, |
| 19 | properties = null, |
| 20 | } ) { |
| 21 | |
| 22 | // context with action props |
| 23 | const { |
| 24 | source, |
| 25 | settings, |
| 26 | setMapField, |
| 27 | } = useContext( CurrentActionEditContext ); |
| 28 | |
| 29 | properties = ( |
| 30 | properties ?? source.properties |
| 31 | ); |
| 32 | |
| 33 | // context with current field in fields map |
| 34 | const { |
| 35 | name, |
| 36 | index, |
| 37 | } = useContext( ActionFieldsMapContext ); |
| 38 | |
| 39 | const { |
| 40 | fields_map = {}, |
| 41 | } = settings; |
| 42 | |
| 43 | function getTypeFieldValue( value ) { |
| 44 | for ( const property of properties ) { |
| 45 | if ( value === property.value ) { |
| 46 | return value; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return parseValue ? parseValue( value ) : dynamic[ 0 ] ?? ''; |
| 51 | } |
| 52 | |
| 53 | const [ currentProp, setCurrentProp ] = useState( |
| 54 | () => getTypeFieldValue( fields_map[ name ] ?? '' ), |
| 55 | ); |
| 56 | |
| 57 | const getHelp = () => { |
| 58 | const property = properties.find( |
| 59 | ( { value } ) => value === currentProp, |
| 60 | ); |
| 61 | |
| 62 | return property?.help ?? ''; |
| 63 | }; |
| 64 | |
| 65 | const FieldSelect = ( |
| 66 | <SelectControl |
| 67 | key={ name + index } |
| 68 | value={ currentProp } |
| 69 | options={ properties } |
| 70 | help={ getHelp() } |
| 71 | onChange={ value => { |
| 72 | const prop = getTypeFieldValue( value ); |
| 73 | |
| 74 | setCurrentProp( prop ); |
| 75 | setMapField( { |
| 76 | nameField: name, |
| 77 | value: dynamic.includes( value ) ? '' : value, |
| 78 | } ); |
| 79 | } } |
| 80 | /> |
| 81 | ); |
| 82 | |
| 83 | return <CurrentPropertyMapContext.Provider value={ { |
| 84 | FieldSelect, |
| 85 | property: currentProp, |
| 86 | } }> |
| 87 | { children && children } |
| 88 | { !children && FieldSelect } |
| 89 | </CurrentPropertyMapContext.Provider>; |
| 90 | } |
| 91 | |
| 92 | export default DynamicPropertySelect; |