| 1 |
/** |
| 2 |
* WordPress dependencies. |
| 3 |
*/ |
| 4 |
import { FormTokenField } from '@wordpress/components'; |
| 5 |
import { useContext, WPElement } from '@wordpress/element'; |
| 6 |
|
| 7 |
/** |
| 8 |
* Internal dependencies. |
| 9 |
*/ |
| 10 |
import { Dispatch } from '../../context'; |
| 11 |
|
| 12 |
/** |
| 13 |
* Linked MultiInput |
| 14 |
* |
| 15 |
* @param {object} props Props. |
| 16 |
* @param {string} props.id Set/Alternative id. |
| 17 |
* @param {object[]} props.synonyms Array of synonyms. |
| 18 |
* @param {string} props.removeAction Name of action to dispatch on remove. |
| 19 |
* @param {string} props.updateAction Name of action to dispatch on update. |
| 20 |
* @returns {WPElement} LinkedMultiInput component |
| 21 |
*/ |
| 22 |
const LinkedMultiInput = ({ id, synonyms, removeAction, updateAction }) => { |
| 23 |
const dispatch = useContext(Dispatch); |
| 24 |
const { removeItemText } = window.epSynonyms.i18n; |
| 25 |
|
| 26 |
/** |
| 27 |
* Handle change to tokens. |
| 28 |
* |
| 29 |
* @param {string[]} value Array of tokens. |
| 30 |
*/ |
| 31 |
const handleChange = (value) => { |
| 32 |
const tokens = value.map((v) => { |
| 33 |
const token = { |
| 34 |
label: v, |
| 35 |
value: v, |
| 36 |
primary: false, |
| 37 |
}; |
| 38 |
|
| 39 |
return token; |
| 40 |
}); |
| 41 |
|
| 42 |
dispatch({ type: updateAction, data: { id, tokens } }); |
| 43 |
}; |
| 44 |
|
| 45 |
/** |
| 46 |
* Handle clearing the synonym. |
| 47 |
*/ |
| 48 |
const handleClear = () => { |
| 49 |
dispatch({ type: removeAction, data: id }); |
| 50 |
}; |
| 51 |
|
| 52 |
return ( |
| 53 |
<> |
| 54 |
<FormTokenField |
| 55 |
key={id} |
| 56 |
label={null} |
| 57 |
onChange={handleChange} |
| 58 |
value={synonyms.map((s) => s.value)} |
| 59 |
/> |
| 60 |
<button className="synonym__remove" type="button" onClick={handleClear}> |
| 61 |
<span className="dashicons dashicons-dismiss" /> |
| 62 |
<span>{removeItemText}</span> |
| 63 |
</button> |
| 64 |
</> |
| 65 |
); |
| 66 |
}; |
| 67 |
|
| 68 |
export default LinkedMultiInput; |
| 69 |
|