EntitySelector.tsx
93 lines
| 1 | import { useState } from 'react'; |
| 2 | import { __ } from '@wordpress/i18n'; |
| 3 | import ReactSelect from 'react-select'; |
| 4 | import logo from './givewp-logo.svg'; |
| 5 | import usePostState from "../../hooks/usePostState"; |
| 6 | import {reactSelectStyles, reactSelectThemeStyles} from "./styles/reactSelectStyles"; |
| 7 | import './styles/index.scss'; |
| 8 | |
| 9 | /** |
| 10 | * @since 4.3.0 |
| 11 | */ |
| 12 | export type EntityOption = { |
| 13 | label: string; |
| 14 | value: number | string; |
| 15 | }; |
| 16 | |
| 17 | /** |
| 18 | * @since 4.3.0 |
| 19 | */ |
| 20 | type EntitySelectorProps = { |
| 21 | id: string; |
| 22 | label: string; |
| 23 | options: EntityOption[]; |
| 24 | isLoading: boolean; |
| 25 | emptyMessage: string; |
| 26 | loadingMessage: string; |
| 27 | onConfirm: (id: number | string) => void; |
| 28 | buttonText?: string; |
| 29 | disabled?: boolean; |
| 30 | }; |
| 31 | |
| 32 | // @ts-ignore |
| 33 | const savePost = () => dispatch('core/editor').savePost(); |
| 34 | |
| 35 | /** |
| 36 | * @since 4.3.0 |
| 37 | */ |
| 38 | export default function EntitySelector({ |
| 39 | id, |
| 40 | label, |
| 41 | options, |
| 42 | isLoading, |
| 43 | emptyMessage, |
| 44 | loadingMessage, |
| 45 | onConfirm, |
| 46 | buttonText = __('Confirm', 'give'), |
| 47 | disabled = false, |
| 48 | }: EntitySelectorProps) { |
| 49 | const [selected, setSelected] = useState<number | string | null>(null); |
| 50 | const selectedOption = options.find((opt) => opt.value === selected); |
| 51 | const {isSaving, isDisabled} = usePostState(); |
| 52 | |
| 53 | return ( |
| 54 | <div className="givewp-entity-selector"> |
| 55 | <img className="givewp-entity-selector__logo" src={logo} alt="givewp-logo" /> |
| 56 | <div className="givewp-entity-selector__select"> |
| 57 | <label htmlFor={id} className="givewp-entity-selector__label"> |
| 58 | {label} |
| 59 | </label> |
| 60 | |
| 61 | <ReactSelect |
| 62 | name={id} |
| 63 | inputId={id} |
| 64 | value={selectedOption} |
| 65 | //@ts-ignore |
| 66 | onChange={(option) => setSelected(option?.value)} |
| 67 | options={options} |
| 68 | noOptionsMessage={() => <p>{emptyMessage}</p>} |
| 69 | loadingMessage={() => <>{loadingMessage}</>} |
| 70 | isLoading={isLoading} |
| 71 | theme={reactSelectThemeStyles} |
| 72 | styles={reactSelectStyles} |
| 73 | placeholder={isLoading ? loadingMessage : __('Select...', 'give')} |
| 74 | /> |
| 75 | </div> |
| 76 | |
| 77 | <button |
| 78 | className="givewp-entity-selector__submit" |
| 79 | type="button" |
| 80 | disabled={isSaving || isDisabled || !selected} |
| 81 | onClick={() => { |
| 82 | if (selected) { |
| 83 | onConfirm(selected); |
| 84 | } |
| 85 | savePost(); |
| 86 | }} |
| 87 | > |
| 88 | {buttonText} |
| 89 | </button> |
| 90 | </div> |
| 91 | ); |
| 92 | } |
| 93 |