PluginProbe
ElasticPress / 4.2.1
ElasticPress v4.2.1
5.3.5 5.3.4 3.6.5 3.6.6 4.0.0 4.0.1 4.1.0 4.2.0 4.2.1 4.2.2 4.3.0 4.3.1 4.4.0 4.4.1 4.5.0 4.5.1 4.5.2 4.6.0 4.6.1 4.7.0 4.7.1 4.7.2 5.0.0 5.0.1 5.0.2 All 108 releases
elasticpress / assets / js / instant-results / admin / components / facet-selector.js

facet-selector.js in ElasticPress 4.2.1, at assets/js/instant-results/admin/components/facet-selector.js

82 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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