| 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 |
|