All files / datepicker datepicker.js

55.1% Statements 27/49
56% Branches 28/50
57.14% Functions 8/14
55.32% Lines 26/47

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                                                                                3x 3x 3x 3x 3x 1x 1x 1x 2x     3x         3x       15x 7x 8x 5x   3x         15x 15x       2x                                                               1x 1x                                         15x 15x 15x         15x     15x                                                                                                                                                              
/*
Copyright (c) 2018-2019 Uber Technologies, Inc.
 
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
import * as React from 'react';
import {Input} from '../input/index.js';
import {Popover, PLACEMENT} from '../popover/index.js';
import Calendar from './calendar.js';
import {formatDate} from './utils/index.js';
import {getOverrides} from '../helpers/overrides.js';
import {LocaleContext} from '../locale/index.js';
import type {DatepickerPropsT} from './types.js';
 
export default class Datepicker extends React.Component<
  DatepickerPropsT,
  {
    calendarFocused: boolean,
    isOpen: boolean,
    isPseudoFocused: boolean,
    lastActiveElm: ?HTMLElement,
  },
> {
  static defaultProps = {
    'aria-describedby': 'datepicker--screenreader--message--input',
    value: null,
  };
 
  calendar: ?HTMLElement;
 
  state = {
    calendarFocused: false,
    isOpen: false,
    isPseudoFocused: false,
    lastActiveElm: null,
  };
 
  onChange = (data: {date: ?Date | Array<Date>}) => {
    const {date} = data;
    let isOpen = false;
    let isPseudoFocused = false;
    let calendarFocused = false;
    if (Array.isArray(date) && this.props.range && date.length < 2) {
      isOpen = true;
      isPseudoFocused = true;
      calendarFocused = null;
    } else Iif (this.state.lastActiveElm) {
      this.state.lastActiveElm.focus();
    }
    this.setState({
      isOpen,
      isPseudoFocused,
      ...(calendarFocused === null ? {} : {calendarFocused}),
    });
    this.props.onChange && this.props.onChange(data);
  };
 
  formatDate(date: ?Date | Array<Date>, formatString: string) {
    if (!date) {
      return '';
    } else if (Array.isArray(date)) {
      return date.map(day => formatDate(day, formatString)).join(' - ');
    } else {
      return formatDate(date, formatString);
    }
  }
 
  formatDisplayValue(date: ?Date | Array<Date>) {
    const formatDisplayValue = this.props.formatDisplayValue || this.formatDate;
    return formatDisplayValue(date, this.props.formatString || 'YYYY/MM/DD');
  }
 
  open = () => {
    this.setState({
      isOpen: true,
      isPseudoFocused: true,
    });
  };
 
  close = () => {
    const isPseudoFocused = false;
    this.setState(
      {
        isOpen: false,
        isPseudoFocused,
        calendarFocused: false,
      },
      this.props.onClose,
    );
  };
 
  handleEsc = () => {
    if (this.state.lastActiveElm) {
      this.state.lastActiveElm.focus();
    }
    this.close();
  };
 
  handleInputBlur = () => {
    if (!this.state.isPseudoFocused) {
      this.close();
    }
  };
 
  handleKeyDown = (event: KeyboardEvent) => {
    Eif (!this.state.isOpen && event.keyCode === 40) {
      this.open();
    } else if (this.state.isOpen && event.key === 'ArrowDown') {
      // next line prevents the page jump on the initial arrowDown
      event.preventDefault();
      this.focusCalendar();
    } else if (this.state.isOpen && event.keyCode === 9) {
      this.close();
    }
  };
 
  focusCalendar = () => {
    if (__BROWSER__) {
      const lastActiveElm = document.activeElement;
      this.setState({
        calendarFocused: true,
        lastActiveElm,
      });
    }
  };
 
  render() {
    const {overrides = {}} = this.props;
    const [InputComponent, inputProps] = getOverrides(overrides.Input, Input);
    const [PopoverComponent, popoverProps] = getOverrides(
      overrides.Popover,
      Popover,
    );
 
    return (
      <LocaleContext.Consumer>
        {locale => (
          <React.Fragment>
            <PopoverComponent
              mountNode={this.props.mountNode}
              placement={PLACEMENT.bottom}
              isOpen={this.state.isOpen}
              onClickOutside={event => {
                // Required to check that items rendered in a sub-popover does not trigger close.
                // For example, upon selecting an option from the month dropdown it would cause
                // this code to run since the two popovers are DOM siblings rather than parent/child.
                // There's likely a more robust way to check this, but ignores clicks from elements
                // that are select options for now.
                function isOption(element) {
                  if (!element) return false;
                  return element.getAttribute('role') === 'option';
                }
                if (
                  isOption(event.target) ||
                  isOption(event.target.parentElement)
                ) {
                  return;
                }
 
                this.close();
              }}
              onEsc={this.handleEsc}
              content={
                <Calendar
                  autoFocusCalendar={this.state.calendarFocused}
                  trapTabbing={true}
                  value={this.props.value}
                  {...this.props}
                  onChange={this.onChange}
                />
              }
              {...popoverProps}
            >
              <span>
                <InputComponent
                  aria-disabled={this.props.disabled}
                  aria-label={
                    this.props['aria-label'] || locale.datepicker.ariaLabel
                  }
                  error={this.props.error}
                  aria-labelledby={this.props['aria-labelledby']}
                  aria-describedby={this.props['aria-describedby']}
                  aria-required={this.props.required || null}
                  disabled={this.props.disabled}
                  value={this.formatDisplayValue(this.props.value)}
                  onFocus={this.open}
                  onBlur={this.handleInputBlur}
                  onKeyDown={this.handleKeyDown}
                  placeholder={this.props.placeholder || 'YYYY/MM/DD'}
                  required={this.props.required}
                  {...inputProps}
                />
              </span>
            </PopoverComponent>
            <p
              id="datepicker--screenreader--message--input"
              style={{
                position: 'absolute',
                width: '1px',
                height: '1px',
                margin: '-1px',
                border: 0,
                padding: 0,
                overflow: 'hidden',
                clip: 'rect(0, 0, 0, 0)',
                clipPath: 'inset(100%)',
              }}
            >
              {locale.datepicker.screenReaderMessageInput}
            </p>
          </React.Fragment>
        )}
      </LocaleContext.Consumer>
    );
  }
}