File size: 2,416 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import { isDefaultLocale } from '@automattic/i18n-utils';
import moment from 'moment-timezone';
import PropTypes from 'prop-types';
import { Component } from 'react';
import AvailableTimeCard from './available-time-card';
const groupAvailableTimesByDate = ( availableTimes, timezone ) => {
const dates = {};
// Go through all available times and bundle them into each date object
availableTimes.forEach( ( beginTimestamp ) => {
const startOfDay = moment( beginTimestamp ).tz( timezone ).startOf( 'day' ).valueOf();
const beginHour = moment.tz( beginTimestamp, timezone ).format( 'HH' );
const isMorning = beginHour < 12;
if ( dates.hasOwnProperty( startOfDay ) ) {
dates[ startOfDay ].times.push( beginTimestamp );
isMorning
? dates[ startOfDay ].morningTimes.push( beginTimestamp )
: dates[ startOfDay ].eveningTimes.push( beginTimestamp );
} else {
const morningTimes = isMorning ? [ beginTimestamp ] : [];
const eveningTimes = isMorning ? [] : [ beginTimestamp ];
dates[ startOfDay ] = {
date: startOfDay,
times: [ beginTimestamp ],
morningTimes,
eveningTimes,
};
}
} );
// Convert the dates object into an array sorted by date and return it
return Object.keys( dates )
.sort()
.map( ( date ) => dates[ date ] );
};
class AvailableTimePicker extends Component {
static propTypes = {
actionText: PropTypes.string.isRequired,
availableTimes: PropTypes.array.isRequired,
appointmentTimespan: PropTypes.number.isRequired,
onSubmit: PropTypes.func.isRequired,
site: PropTypes.object.isRequired,
timezone: PropTypes.string.isRequired,
};
render() {
const {
actionText,
availableTimes,
appointmentTimespan,
currentUserLocale,
disabled,
onSubmit,
timezone,
} = this.props;
const availability = groupAvailableTimesByDate( availableTimes, timezone );
return (
<div>
{ availability.map( ( { date, times, morningTimes, eveningTimes } ) => (
<AvailableTimeCard
actionText={ actionText }
appointmentTimespan={ appointmentTimespan }
date={ date }
disabled={ disabled }
isDefaultLocale={ isDefaultLocale( currentUserLocale ) }
key={ date }
onSubmit={ onSubmit }
times={ times }
morningTimes={ morningTimes }
eveningTimes={ eveningTimes }
timezone={ timezone }
/>
) ) }
</div>
);
}
}
export default AvailableTimePicker;
|