| 1 |
/** |
| 2 |
* WordPress dependencies. |
| 3 |
*/ |
| 4 |
import { Fragment, useContext, WPElement } from '@wordpress/element'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Internal dependencies. |
| 8 |
*/ |
| 9 |
import { Dispatch, State } from '../../context'; |
| 10 |
import AlternativeEditor from './AlternativeEditor'; |
| 11 |
|
| 12 |
/** |
| 13 |
* Synonyms editor component. |
| 14 |
* |
| 15 |
* @param {object} props Props. |
| 16 |
* @param {object[]} props.alternatives Defined alternatives (explicit mappings). |
| 17 |
* @returns {WPElement} AlternativesEditor component |
| 18 |
*/ |
| 19 |
const AlternativesEditor = ({ alternatives }) => { |
| 20 |
const dispatch = useContext(Dispatch); |
| 21 |
const state = useContext(State); |
| 22 |
const { |
| 23 |
alternativesInputHeading, |
| 24 |
alternativesPrimaryHeading, |
| 25 |
alternativesAddButtonText, |
| 26 |
alternativesErrorMessage, |
| 27 |
} = window.epSynonyms.i18n; |
| 28 |
|
| 29 |
/** |
| 30 |
* Handle click. |
| 31 |
* |
| 32 |
* @param {Event} e Event. |
| 33 |
*/ |
| 34 |
const handleClick = (e) => { |
| 35 |
const [lastItem] = state.alternatives.slice(-1); |
| 36 |
if (!alternatives.length || lastItem.synonyms.filter(({ value }) => value.length).length) { |
| 37 |
dispatch({ type: 'ADD_ALTERNATIVE' }); |
| 38 |
} |
| 39 |
e.preventDefault(); |
| 40 |
}; |
| 41 |
|
| 42 |
return ( |
| 43 |
<div className="synonym-alternatives-editor metabox-holder"> |
| 44 |
<div className="postbox"> |
| 45 |
<h2 className="hndle"> |
| 46 |
<span className="synonym-alternatives__primary-heading"> |
| 47 |
{alternativesPrimaryHeading} |
| 48 |
</span> |
| 49 |
<span className="synonym-alternatives__input-heading"> |
| 50 |
{alternativesInputHeading} |
| 51 |
</span> |
| 52 |
</h2> |
| 53 |
<div className="inside"> |
| 54 |
{alternatives.map((props) => ( |
| 55 |
<Fragment key={props.id}> |
| 56 |
<div className="synonym-alternative-editor"> |
| 57 |
<AlternativeEditor |
| 58 |
{...props} |
| 59 |
updateAction="UPDATE_ALTERNATIVE" |
| 60 |
removeAction="REMOVE_ALTERNATIVE" |
| 61 |
/> |
| 62 |
</div> |
| 63 |
{!props.valid && ( |
| 64 |
<p className="synonym__validation">{alternativesErrorMessage}</p> |
| 65 |
)} |
| 66 |
</Fragment> |
| 67 |
))} |
| 68 |
<button type="button" className="button button-secondary" onClick={handleClick}> |
| 69 |
{alternativesAddButtonText} |
| 70 |
</button> |
| 71 |
</div> |
| 72 |
</div> |
| 73 |
</div> |
| 74 |
); |
| 75 |
}; |
| 76 |
|
| 77 |
export default AlternativesEditor; |
| 78 |
|