# All files / composer/components DateTimeSlotPicker.jsx

49.28% Statements 34/69
42.22% Branches 19/45
37.5% Functions 6/16
50.77% Lines 33/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296

    1x
    1x
    1x

    1x
    1x

    1x

    1x

    1x

    1x

    1x

    140x

    1x

    1x

    1x

    1x

    1x
    1x

    1x

    1x

    1x

    2x

    2x

    2x
    2x

    2x

    70x
    70x
    70x

    2x
    2x

    2x
    2x

    2x

     /**
     * Date + time picker combo!
     *
     * DateTimeSlotPicker is timezone-aware, and works with 12/24h formats. If the
     * component is passed a different timezone through props after it's been
     * mounted, it'll update the date and time to that new timezone and go on with
     * its business. The component also ensures the selected date and time are in
     * the future, no matter the timezone.
     *
     * This component is uncontrolled (except for the timezone prop), and uses the
     * onSubmit callback in props to let its parent know of any scheduling action.
     */

    import React from 'react';
    import PropTypes from 'prop-types';
    import moment from 'moment-timezone';
    import TimePicker from '../components/TimePicker';
    import SlotPicker from '../components/SlotPicker';
    import Button from '../components/Button';
    import Select from '../components/Select';

    import { InputDate } from '@bufferapp/components';
    import styles from './css/DateTimeSlotPicker.css';

    class DateTimeSlotPicker extends React.Component {
      getState() {
        const { timezone, initialDateTime } = this.props;
        const todayDate = (new Date()).setSeconds(0); // Seconds must be 0 for precise scheduling
        const isTimezoneSet = !!timezone;

        // Determine initial date and time for the picker
        const today = isTimezoneSet ? moment.tz(todayDate, timezone) : moment(todayDate);
        const selectedDateTime = initialDateTime || today.clone().add(3, 'hours');
        const shouldDisplaySlotPicker =
          this.shouldDisplaySlotPickerOnInit(selectedDateTime, this.props);

        return {
          today,
          selectedDateTime,
          shouldDisplaySlotPicker,
        };
      }

      shouldDisplaySlotPickerOnInit = (selectedDateTime, props) => {
        const { isSlotPickingAvailable, availableSchedulesSlotsForDay } = props;

        const hasAvailableSchedulesSlotsInfoForDay =
          typeof availableSchedulesSlotsForDay !== 'undefined';

        Eif (!isSlotPickingAvailable || !hasAvailableSchedulesSlotsInfoForDay) return undefined;

        const selectedTimestamp = selectedDateTime.unix();
        const isAnySlotSelected =
          availableSchedulesSlotsForDay.some((slot) => slot.timestamp === selectedTimestamp);

        return isAnySlotSelected && props.isPinnedToSlot;
      };

      static propTypes = {
        shouldUse24hTime: PropTypes.bool.isRequired,
        onSubmit: PropTypes.func.isRequired,
        isSlotPickingAvailable: PropTypes.bool,
        onClick: PropTypes.func,
        onChange: PropTypes.func,
        timezone: PropTypes.string,
        weekStartsMonday: PropTypes.bool.isRequired,
        availableSchedulesSlotsForDay: PropTypes.oneOfType([
          PropTypes.bool,
          PropTypes.arrayOf(PropTypes.shape({
            isSlotFree: PropTypes.bool.isRequired,
            timestamp: PropTypes.number.isRequired,
          })),
        ]),
        isPinnedToSlot: PropTypes.bool,
        metaData: PropTypes.object,
        initialDateTime: PropTypes.instanceOf(moment),
        submitButtonCopy: PropTypes.string,
      };

      static defaultProps = {
        shouldUse24hTime: false,
        isSlotPickingAvailable: false,
        onClick: () => {},
        onChange: () => {},
        timezone: 'Europe/Paris',
        submitButtonCopy: 'Schedule',
        availableSchedulesSlotsForDay: undefined,
        isPinnedToSlot: null,
        metaData: undefined,
      };

      state = this.getState();

      updateDate = (date) => {
        const year = date.getFullYear();
        const month = date.getMonth();
        const day = date.getDate();
        const newSelectedDateTime = this.state.selectedDateTime.year(year).month(month).date(day);
        const isPinnedToSlot = this.state.shouldDisplaySlotPicker;

        this.setState({
          selectedDateTime: newSelectedDateTime,
        });

        this.props.onChange(newSelectedDateTime, isPinnedToSlot);
      };

      updateTime = (time) => {
        const hours = time.hours();
        const minutes = time.minutes();
        const newSelectedDateTime = this.state.selectedDateTime.hour(hours).minute(minutes);
        const isPinnedToSlot = this.state.shouldDisplaySlotPicker;

        this.setState({
          selectedDateTime: newSelectedDateTime,
        });

        this.props.onChange(newSelectedDateTime, isPinnedToSlot);
      };

      // Set to UTC, then negate the original offset
      stripOffsetFromMoment = (m) => m.clone().utc().add(m.utcOffset(), 'm');

      onClick = this.props.onClick; // eslint-disable-line react/sort-comp

      onDayClick = (day) => {
        this.updateDate(day);
      };

      onTimePickerChange = this.updateTime;
      onSlotPickerChange = this.updateTime;

      onSwitchToSlotPickerClick = () => {
        // Update UI state
        this.setState({ shouldDisplaySlotPicker: true });

        // If a slot is available for the current date time, update store to
        // transition from custom time to pinned update mode
        const { isSlotPickingAvailable, availableSchedulesSlotsForDay } = this.props;

        const hasAvailableSchedulesSlotsInfoForDay =
          typeof availableSchedulesSlotsForDay !== 'undefined';

        if (!isSlotPickingAvailable || !hasAvailableSchedulesSlotsInfoForDay) return;

        const selectedTimestamp = this.state.selectedDateTime.unix();
        const hasSlotAvailableForSelectedDateTime =
          availableSchedulesSlotsForDay.some((slot) => slot.timestamp === selectedTimestamp);

        const isPinnedToSlot = hasSlotAvailableForSelectedDateTime;
        this.props.onChange(this.state.selectedDateTime, isPinnedToSlot);
      };

      onSwitchToTimePickerClick = () => {
        const isPinnedToSlot = false;

        this.setState({ shouldDisplaySlotPicker: isPinnedToSlot });
        this.props.onChange(this.state.selectedDateTime, isPinnedToSlot);
      };

      onSubmit = () => this.props.onSubmit(this.state.selectedDateTime.unix());

      componentWillReceiveProps(nextProps) {
        const { today, selectedDateTime, shouldDisplaySlotPicker } = this.state;

        // Update selectedDateTime with the new timezone if it changes
        Iif (this.props.timezone !== nextProps.timezone && nextProps.timezone !== null) {
          this.setState({
            today: today.tz(nextProps.timezone),
            selectedDateTime: selectedDateTime.tz(nextProps.timezone),
          });
        }

        /**
         * MC is only bootstrapped with limited slot info: if it gets initialized with
         * a scheduledAt date that falls outside of this bootstrapped slot coverage,
         * we'll try determining whether to start in "slot picker mode" or not once
         * we've got additional slot info at our disposal.
         */
        const willSlotPickingBeAvailable = nextProps.isSlotPickingAvailable;
        const hasAvailableSchedulesSlotsInfoForDay =
          typeof this.props.availableSchedulesSlotsForDay !== 'undefined';
        const willHaveAvailableSchedulesSlotsInfoForDay =
          typeof nextProps.availableSchedulesSlotsForDay !== 'undefined';
        const didInitSlotPickerDisplayState = typeof shouldDisplaySlotPicker !== 'undefined';

        const shouldInitSlotPickerDisplayInfo = (
          willSlotPickingBeAvailable &&
          !hasAvailableSchedulesSlotsInfoForDay &&
          willHaveAvailableSchedulesSlotsInfoForDay &&
          !didInitSlotPickerDisplayState
        );

        Iif (shouldInitSlotPickerDisplayInfo) {
          this.setState({
            shouldDisplaySlotPicker: this.shouldDisplaySlotPickerOnInit(selectedDateTime, nextProps),
          });
        }

        // Keep store and component state in sync
        Iif (this.props.isPinnedToSlot !== nextProps.isPinnedToSlot) {
          this.setState({
            shouldDisplaySlotPicker: nextProps.isPinnedToSlot,
          });
        }
      }

      render() {
        const { today, selectedDateTime, shouldDisplaySlotPicker } = this.state;
        const {
          metaData, timezone, shouldUse24hTime, submitButtonCopy, isSlotPickingAvailable,
          availableSchedulesSlotsForDay,
        } = this.props;

        const hasAvailableSchedulesSlotsInfoForDay =
          typeof availableSchedulesSlotsForDay !== 'undefined';
        const shouldDisplayTimePicker = !shouldDisplaySlotPicker;

        const selectedDays = {
          selected: (day) => {
            const selectedDateTimeNoOffset = this.stripOffsetFromMoment(selectedDateTime);
            const dayNoOffset = this.stripOffsetFromMoment(moment(day));
            return selectedDateTimeNoOffset.isSame(dayNoOffset, 'day');
          },
        };

        const shouldDisplayTimezone = timezone !== null;
        const isTimeInFuture = selectedDateTime.isAfter();
        const formattedTimezone =
          shouldDisplayTimezone ? timezone.replace('/', ': ').replace('_', ' ') : null;
        const firstDayOfWeek = this.props.weekStartsMonday ? 1 : 0;

        return (
          <div onClick={this.onClick} className={styles.dateTimePicker}>

            <InputDate
              initialMonth={new Date()}
              onDayClick={this.onDayClick}
              selectedDays={selectedDays.selected}
              firstDayOfWeek={firstDayOfWeek}
            />

            {shouldDisplayTimePicker &&
              <TimePicker
                shouldUse24hTime={shouldUse24hTime} time={selectedDateTime}
                timezone={timezone} onChange={this.onTimePickerChange}
                className={styles.timePicker}
              />}

            {shouldDisplayTimePicker && isSlotPickingAvailable &&
              <Button
                className={styles.pickerSwitchButton}
                onClick={this.onSwitchToSlotPickerClick}
              >
                Switch to schedule slots
              </Button>}

            {shouldDisplaySlotPicker && isSlotPickingAvailable &&
            (hasAvailableSchedulesSlotsInfoForDay ?
              <SlotPicker
                metaData={metaData}
                shouldUse24hTime={shouldUse24hTime}
                timezone={timezone}
                slots={availableSchedulesSlotsForDay}
                slot={selectedDateTime}
                onChange={this.onSlotPickerChange}
                className={styles.slotPicker}
              /> :
              <Select disabled className={styles.slotPicker} value="">
                <option value="">Loading slots…</option>
              </Select>)}

            {shouldDisplaySlotPicker && isSlotPickingAvailable &&
              <Button
                className={styles.pickerSwitchButton}
                onClick={this.onSwitchToTimePickerClick}
              >
                Switch to custom time
              </Button>}

            <Button
              onClick={this.onSubmit} className={styles.submitButton}
              disabled={!isTimeInFuture}
            >
              {submitButtonCopy}
            </Button>

            {shouldDisplayTimezone &&
              <div className={styles.timezone}>{formattedTimezone}</div>}
          </div>
        );
      }
    }

    export default DateTimeSlotPicker;