| 1 |
/** |
| 2 |
* WordPress dependencies. |
| 3 |
*/ |
| 4 |
import { FormTokenField } from '@wordpress/components'; |
| 5 |
import { useMemo, useState, WPElement } from '@wordpress/element'; |
| 6 |
import { __ } from '@wordpress/i18n'; |
| 7 |
|
| 8 |
/** |
| 9 |
* Internal dependencies. |
| 10 |
*/ |
| 11 |
import { facets } from '../config'; |
| 12 |
|
| 13 |
/** |
| 14 |
* Facet selector component. |
| 15 |
* |
| 16 |
* @param {object} props Props. |
| 17 |
* @param {string} props.defaultValue Default value. |
| 18 |
* @returns {WPElement} Element. |
| 19 |
*/ |
| 20 |
export default ({ defaultValue, ...props }) => { |
| 21 |
const defaultValues = defaultValue.split(','); |
| 22 |
const [selectedFacets, setSelectedFacets] = useState(defaultValues); |
| 23 |
|
| 24 |
/** |
| 25 |
* Get the label for a facet from the facet key. |
| 26 |
* |
| 27 |
* @param {string} key Facet key. |
| 28 |
* @returns {string} Facet label. |
| 29 |
*/ |
| 30 |
const getLabelFromKey = (key) => { |
| 31 |
return facets[key]?.label; |
| 32 |
}; |
| 33 |
|
| 34 |
/** |
| 35 |
* Get the key for a facet from the facet label. |
| 36 |
* |
| 37 |
* @param {string} label Facet label. |
| 38 |
* @returns {string} Facet key. |
| 39 |
*/ |
| 40 |
const getKeyFromLabel = (label) => { |
| 41 |
return Object.keys(facets).find((key) => { |
| 42 |
return label === facets[key].label; |
| 43 |
}); |
| 44 |
}; |
| 45 |
|
| 46 |
/** |
| 47 |
* Suggestions for the token field. |
| 48 |
*/ |
| 49 |
const suggestions = useMemo(() => Object.keys(facets).map(getLabelFromKey).filter(Boolean), []); |
| 50 |
|
| 51 |
/** |
| 52 |
* Values for the token field. |
| 53 |
*/ |
| 54 |
const value = useMemo( |
| 55 |
() => selectedFacets.map(getLabelFromKey).filter(Boolean), |
| 56 |
[selectedFacets], |
| 57 |
); |
| 58 |
|
| 59 |
/** |
| 60 |
* Handle change to token field. |
| 61 |
* |
| 62 |
* @param {Array} tokens Selected tokens. |
| 63 |
*/ |
| 64 |
const onChange = (tokens) => { |
| 65 |
setSelectedFacets(tokens.map(getKeyFromLabel).filter(Boolean)); |
| 66 |
}; |
| 67 |
|
| 68 |
return ( |
| 69 |
<> |
| 70 |
<FormTokenField |
| 71 |
__experimentalExpandOnFocus |
| 72 |
__experimentalShowHowTo={false} |
| 73 |
label={__('Select facets', 'elasticpress')} |
| 74 |
onChange={onChange} |
| 75 |
suggestions={suggestions} |
| 76 |
value={value} |
| 77 |
/> |
| 78 |
<input type="hidden" value={selectedFacets.join(',')} {...props} /> |
| 79 |
</> |
| 80 |
); |
| 81 |
}; |
| 82 |
|