import {TimePicker} from '@wordpress/components'; import ButtonGroup from '../components/ButtonGroup'; import {__} from '@wordpress/i18n'; import {useEffect} from '@wordpress/element'; // Helperfunction: Parse String (HH:MM) in date object const parseTimeToDate = ( timeStr ) => { if ( !timeStr ) { return null; } if ( timeStr instanceof Date ) { return timeStr; } const [h, m] = String( timeStr ).split( ':' ).map( Number ); if ( Number.isNaN( h ) || Number.isNaN( m ) ) { return null; } const d = new Date(); d.setHours( h, m, 0, 0 ); return d; }; // Helperfunction: Format ISO-String back in HH:MM const formatIsoToTime = ( isoString ) => { if ( !isoString ) { return ''; } const date = new Date( isoString ); if ( isNaN( date.getTime() ) ) { return ''; } const h = String( date.getHours() ).padStart( 2, '0' ); const m = String( date.getMinutes() ).padStart( 2, '0' ); return `${h}:${m}`; }; const ScheduleTimeField = ( {field, allMetaData, onDataChange} ) => { const disabled = (field.premium || field.disabled) ?? false; const mode = allMetaData['schedule_time_mode'] || 'all_day'; const startMeta = allMetaData['schedule_time_start']; const endMeta = allMetaData['schedule_time_end']; const start = startMeta || '00:00'; const end = endMeta || '23:59'; const startDate = parseTimeToDate( start ); const endDate = parseTimeToDate( end ); useEffect( () => { if ( mode === 'scheduled' ) { if ( !startMeta ) { onDataChange( 'schedule_time_start', '00:00' ); } if ( !endMeta ) { onDataChange( 'schedule_time_end', '23:59' ); } } }, [mode, startMeta, endMeta, onDataChange] ); return (
onDataChange( 'schedule_time_mode', val )} disabled={disabled} /> {mode === 'scheduled' && ( // @wordpress/components' TimePicker has no disabled prop of its own
{ if ( disabled ) { return; } // newIsoString is here e.g. "2023-10-25T14:00:00" const timeString = formatIsoToTime( newIsoString ); onDataChange( 'schedule_time_start', timeString ); }} is12Hour={false} />
{__( 'until', 'adpresso' )}
{ if ( disabled ) { return; } const timeString = formatIsoToTime( newIsoString ); onDataChange( 'schedule_time_end', timeString ); }} is12Hour={false} />
)}
); }; export default ScheduleTimeField;