index.js
73 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 | const { __ } = wp.i18n; |
| 13 | |
| 14 | const DateTimeControl = ( { name, label, help, className, value, onChange } ) => { |
| 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( '' ).reverse().join( '' ) // Reverse the string and test for "a" not followed by a slash |
| 26 | ); |
| 27 | return ( |
| 28 | <BaseControl |
| 29 | label={ label } |
| 30 | hideLabelFromVision={ true } |
| 31 | id={ id } |
| 32 | help={ help } |
| 33 | className={ className } |
| 34 | > |
| 35 | <div style={ { display: 'flex', alignItems: 'center', justifyContent: 'space-between' } }> |
| 36 | <span> |
| 37 | { label } |
| 38 | </span> |
| 39 | <Dropdown |
| 40 | position="bottom right" |
| 41 | renderToggle={ ( { isOpen, onToggle } ) => ( |
| 42 | <Button isSecondary onClick={ onToggle } aria-expanded={ isOpen }> |
| 43 | { value !== '' ? date( 'F j, Y', value ) : __( 'Set date', 'give' ) } |
| 44 | </Button> |
| 45 | ) } |
| 46 | renderContent={ () => ( |
| 47 | <DateTimePicker |
| 48 | currentDate={ value } |
| 49 | onChange={ ( newValue ) => onChange( newValue ) } |
| 50 | is12Hour={ is12HourTime } |
| 51 | /> |
| 52 | ) } |
| 53 | /> |
| 54 | </div> |
| 55 | </BaseControl> |
| 56 | ); |
| 57 | }; |
| 58 | |
| 59 | DateTimeControl.propTypes = { |
| 60 | label: PropTypes.string, |
| 61 | value: PropTypes.any.isRequired, |
| 62 | onChange: PropTypes.func, |
| 63 | name: PropTypes.string.isRequired, |
| 64 | help: PropTypes.string, |
| 65 | className: PropTypes.string, |
| 66 | }; |
| 67 | |
| 68 | DateTimeControl.defaultProps = { |
| 69 | onChange: null, |
| 70 | }; |
| 71 | |
| 72 | export default DateTimeControl; |
| 73 |