index.js
63 lines
| 1 | /** |
| 2 | * Vendor dependencies |
| 3 | */ |
| 4 | import PropTypes from 'prop-types'; |
| 5 | |
| 6 | /** |
| 7 | * WordPress dependencies |
| 8 | */ |
| 9 | const {useInstanceId} = wp.compose; |
| 10 | const {DateTimePicker, BaseControl, Button, Dropdown} = wp.components; |
| 11 | const {__experimentalGetSettings, date} = wp.date; |
| 12 | import { __ } from '@wordpress/i18n' |
| 13 | |
| 14 | const DateTimeControl = ({name, label, help, className, value, onChange = null}) => { |
| 15 | const instanceId = useInstanceId(DateTimeControl); |
| 16 | const id = `give-date-time-control-${name}-${instanceId}`; |
| 17 | const settings = __experimentalGetSettings(); // eslint-disable-line no-restricted-syntax |
| 18 | |
| 19 | // To know if the current timezone is a 12 hour time with look for an "a" in the time format. |
| 20 | // We also make sure this a is not escaped by a "/". |
| 21 | const is12HourTime = /a(?!\\)/i.test( |
| 22 | settings.formats.time |
| 23 | .toLowerCase() // Test only the lower case a |
| 24 | .replace(/\\\\/g, '') // Replace "//" with empty strings |
| 25 | .split('') |
| 26 | .reverse() |
| 27 | .join('') // Reverse the string and test for "a" not followed by a slash |
| 28 | ); |
| 29 | return ( |
| 30 | <BaseControl label={label} hideLabelFromVision={true} id={id} help={help} className={className}> |
| 31 | <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}> |
| 32 | <span>{label}</span> |
| 33 | <Dropdown |
| 34 | position="bottom right" |
| 35 | renderToggle={({isOpen, onToggle}) => ( |
| 36 | <Button isSecondary onClick={onToggle} aria-expanded={isOpen}> |
| 37 | {value !== '' ? date('F j, Y', value) : __('Set date', 'give')} |
| 38 | </Button> |
| 39 | )} |
| 40 | renderContent={() => ( |
| 41 | <DateTimePicker |
| 42 | currentDate={value} |
| 43 | onChange={(newValue) => onChange(newValue)} |
| 44 | is12Hour={is12HourTime} |
| 45 | /> |
| 46 | )} |
| 47 | /> |
| 48 | </div> |
| 49 | </BaseControl> |
| 50 | ); |
| 51 | }; |
| 52 | |
| 53 | DateTimeControl.propTypes = { |
| 54 | label: PropTypes.string, |
| 55 | value: PropTypes.any.isRequired, |
| 56 | onChange: PropTypes.func, |
| 57 | name: PropTypes.string.isRequired, |
| 58 | help: PropTypes.string, |
| 59 | className: PropTypes.string, |
| 60 | }; |
| 61 | |
| 62 | export default DateTimeControl; |
| 63 |