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 / synonyms / components / editors / AlternativeEditor.js

AlternativeEditor.js in ElasticPress 4.2.1, at assets/js/synonyms/components/editors/AlternativeEditor.js

89 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 { useContext, useEffect, useMemo, useRef, useState, WPElement } from '@wordpress/element';
5
6 /**
7 * Internal dependencies.
8 */
9 import { Dispatch } from '../../context';
10 import LinkedMultiInput from '../shared/LinkedMultiInput';
11
12 /**
13 * Alternative Editor
14 *
15 * @param {object} props Props.
16 * @returns {WPElement} AlternativeEditor component
17 */
18 const AlternativeEditor = (props) => {
19 const { id, synonyms, removeAction, updateAction } = props;
20 const primary = synonyms.find((item) => item.primary);
21 const [primaryTerm, setPrimaryTerm] = useState(primary ? primary.value : '');
22 const dispatch = useContext(Dispatch);
23 const primaryRef = useRef(null);
24
25 /**
26 * Create primary token
27 *
28 * @param {string} label Label.
29 * @returns {object} Primary token
30 */
31 const createPrimaryToken = (label) => {
32 return {
33 label,
34 value: label,
35 primary: true,
36 };
37 };
38
39 /**
40 * Handle key down.
41 *
42 * @param {Event} event Keydown event.
43 */
44 const handleKeyDown = (event) => {
45 switch (event.key) {
46 case 'Enter':
47 event.preventDefault();
48 break;
49 default:
50 }
51 };
52
53 useEffect(() => {
54 dispatch({
55 type: 'UPDATE_ALTERNATIVE_PRIMARY',
56 data: { id, token: createPrimaryToken(primaryTerm) },
57 });
58 }, [primaryTerm, id, dispatch]);
59
60 useEffect(() => {
61 primaryRef.current.focus();
62 }, [primaryRef]);
63
64 const memoizedSynonyms = useMemo(() => {
65 return synonyms.filter((item) => !item.primary);
66 }, [synonyms]);
67
68 return (
69 <>
70 <input
71 type="text"
72 className="ep-synonyms__input"
73 onChange={(e) => setPrimaryTerm(e.target.value)}
74 value={primaryTerm}
75 onKeyDown={handleKeyDown}
76 ref={primaryRef}
77 />
78 <LinkedMultiInput
79 id={id}
80 updateAction={updateAction}
81 removeAction={removeAction}
82 synonyms={memoizedSynonyms}
83 />
84 </>
85 );
86 };
87
88 export default AlternativeEditor;
89