All files / src TimePicker.js

96% Statements 48/50
72.73% Branches 24/33
100% Functions 20/20
96% Lines 48/50

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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360                            7x     7x   7x 7x                                               7x 7x 7x                                             1x                     8x                   11x                       12x 4x   8x                     2x         2x   2x       2x                         10x 10x                           1x             1x         1x   1x       1x                     1x   1x 1x                   6x 2x     6x                   4x 2x     4x                 2x 2x   2x                     24x                         1x                   1x                           17x                               17x 17x     17x   17x                                     25x                                             1x                               1x 1x      
import React from 'react'
import PropTypes from 'prop-types'
import {omit} from 'lodash'
import TimeInput from './TimePicker/TimeInput'
import TimeContainer from './TimePicker/TimeContainer'
import InputHelpText from './InputHelpText'
import InputErrors from './InputErrors'
import {DateTime} from 'luxon'
 
/**
 * Determines if time type inputs are well supported on this platform
 * @return {boolean} true if time type inputs are well supported, false otherwise
 */
function useGoodTimeInput() {
  Iif (typeof window === 'undefined') {
    return true
  } else {
    const element = document.createElement('input')
 
    element.type = 'time'
    return element.type === 'time'
  }
}
 
/* TODO FEATURES:
    allow keyboard up & down to increment/decrement for accessibility concerns,
    overrides,
    allow setting how much each button should increment,
    allowing min and/or max times to be declared,
    maybe giving ability to disallow certain times to be selected?
      ^ might not need it if combination of min/max times and setting
        increment amounts achieves same purpose
*/
 
/**
 * A TimePicker component containing inputs and a container with two to four ticker
 * components for hours, minutes, an optional seconds, and an optional AM/PM. */
class TimePicker extends React.Component {
  /**
   * Create a time picker. Determines if we can use browser native time type input
   * or if we need to fall back to a text type input (based on support).
   * @param {object} props - the props
   */
  constructor(props) {
    super(props)
    this.useGoodTimeInput = useGoodTimeInput()
    this.state = {
      isOpen: this.props.isOpen || false,
      focused: false,
      // Handles setting both the iso and 'local' format versions of the time
      // into state. We do this so that we can always accept ISO times from
      // up the hierarchy, but also handle accepting change events from unchecked
      // oddly formatted text inputs
      ...this.valuesFromProps(props),
      // Generation exists to force the inputs in the component to accept the
      // new value when we click a ticker
      generation: 0,
      mousedIn: false,
    }
  }
 
  /**
   * Handle updated props from up the chain. In particular, if we receive a new
   * time from up the hierarchy, we want to reset the inputs and the tickers to
   * that value.
   * @param {object} nextProps - the nextProps
   * @return {void}
   */
  componentWillReceiveProps(nextProps) {
    this.setState(this.valuesFromProps(nextProps))
  }
 
  /**
   * Find the time value from the props, and convert it to two values-- an iso
   * time and a 'local' format time version (so we can deal with poorly formatted
   * text inputs intelligently).
   * @param {object} props - the props
   * @return {object} an object with two keys: isoValue & formattedValue
   */
  valuesFromProps(props) {
    return this.valuesFromIso(props.defaultValue || props.value)
  }
 
  /**
   * Take an ISO formatted time and turn it into an object with iso and local
   * format time.
   * @param {string} iso - an iso format time
   * @return {object} an object with two keys: isoValue & formattedValue
   */
  valuesFromIso(iso) {
    return {
      isoValue: iso,
      formattedValue: this.isoToFormatted(iso),
    }
  }
 
  /**
   * Take an iso formatted time and put it into this picker's format
   * @param {string} iso - an iso format time
   * @return {string} a time formatted according to the format of this time picker
   */
  isoToFormatted(iso) {
    if (!iso) {
      return ''
    }
    return DateTime.fromISO(iso).toFormat(this.timeFormat)
  }
 
  /**
   * Process change events from the input by updating the isoValue & formattedValue
   * of this component. Will call down to an onChange handler passed in.
   * @param {Event} event - the change event fired from the input
   * @return {void}
   */
  onChange(event) {
    // Take whatever format the input gave us, and turn it into an ISO time string
    const asISO = DateTime.fromFormat(
      event.target.value,
      this.timeFormat
    ).toISOTime()
 
    Eif (this.props.onChange) {
      // Call into an onChange we got as props
      this.props.onChange(event)
    }
 
    // Update isoValue & formattedValue from the ISO we built
    this.setState(this.valuesFromIso(asISO))
  }
 
  /**
   * Return the time format the component is using. Will be 'HH:mm' (or HH:mm:ss if seconds are to be
   * shown) if we are using a well supported time input. If we have fallen back
   * to text field due to bad support, this will be 'hh:mm a' (or 'hh:mm:ss a' if seconds are to be shown).
   * @return {string} the time format in use by the component
   */
  /* eslint complexity: [2, 4] */
  get timeFormat() {
    // TODO: detect locale default format string and use that instead of
    //   hardcoded 'HH:mm'
    Eif (this.useGoodTimeInput) {
      return this.props.showSeconds ? 'HH:mm:ss' : 'HH:mm'
    }
    return this.props.showSeconds ? 'hh:mm:ss a' : 'hh:mm a'
  }
 
  /**
   * Invoked by a time ticker to tell the time picker to update the inputs (onClick
   * of the ticker buttons).
   * @param {string} time - the new time, in the format hh:mm
   * @return {void}
   */
  updateTime(time) {
    // Update isoValue & formattedValue based on the time value (which is an iso
    // time)
    this.setState(this.valuesFromIso(time), () => {
      // Update the native input value with the formatted version of the new time
      // (this prevents the native input value from sticking with a hand-typed
      // input value after the button is clicked in certain situations)
      // It also sets us up to fire off a synthetic change event that looks just
      // like change event from a typed input (so external change handlers are
      // properly) invoked
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
        window.HTMLInputElement.prototype,
        'value'
      ).set
 
      nativeInputValueSetter.call(this.nativeInput, this.isoToFormatted(time));
 
      this.fireChangeHandler()
 
      // Force the input to be focused again (so that we don't immediately close
      // the ticker container because the button click makes us not focused on the input)
      this.refocusOnClick()
    })
  }
 
  /**
   * Create a synthetic change event and send it into the change handlers as if
   * the user had typed the new value. This makes typed input and time ticker button
   * clicks fire off the same handlers.
   * @return {void}
   */
  fireChangeHandler() {
    const event = new Event('change', {bubbles: true, cancelable: false})
 
    this.nativeInput.dispatchEvent(event)
    this.onChange(event)
  }
 
  /**
   * Mark the input as in focus. Used to determine whether the time ticker container should
   * be open.
   * @param {Event} event - the focus event
   * @return {void}
   */
  onFocus(event) {
    if (this.props.onFocus) {
      this.props.onFocus(event)
    }
 
    this.setState({focused: true, isOpen: true})
  }
 
  /**
   * Mark the input as out of focus. Used to determine whether the time ticker container should
   * be closed.
   * @param {Event} event - the blur event
   * @return {void}
   */
  onBlur(event) {
    if (this.props.onBlur) {
      this.props.onBlur(event)
    }
 
    this.setState({focused: false, isOpen: this.state.mousedIn})
  }
 
  /**
   * Force the input back into focus. Used when time ticker buttons are clicked, so
   * that the input stays in focus and we don't close the container.
   * @return {void}
   */
  refocusOnClick() {
    Eif (this.nativeInput) {
      this.nativeInput.focus()
    }
    this.onFocus()
  }
 
  /**
   * Test whether we're on android or iphone. In that case, we hide the time picker
   * (unless we specify the usePickerOnMobile prop to force it). This is because
   * those platforms have native inputs for time which are much better for touch
   * than what we can do with time tickers.
   * @return {boolean} - true if on iOS or Android
   */
  useNativePicker() {
    return (
      typeof navigator !== 'undefined' &&
      /Android|iPhone|iPad|iPod/i.test(navigator.userAgent)
    )
  }
 
  /**
   * Track when the mouse cursor is over the component, so that we can not
   * immediately close the container when we lose focus-- which happens if you
   * click the container buttons.
   * @return {void}
   */
  mouseIn() {
    this.setState({mousedIn: true})
  }
 
  /**
   * Track when the mouse is no longer over the component, which means that it
   * is safe to close the container if we lose focus, for example, because the
   * focus has moved to the next element.
   * @return {void}
   */
  mouseOut() {
    this.setState({mousedIn: false, isOpen: this.state.focused})
  }
 
  /**
   * Returns true if the time container is opened, which is if:
   * - isOpen prop or state is set to true (state is true if the input is in focus)
   * - AND the input is not disabled
   * - AND we're not using the iOS / Android native picker (i.e. we're not on
   *   those platform OR we used props.useContainerOnMobile to force non-native
   *   input)
   * @returns {boolean} - true if the time container is open
   */
  /* eslint complexity: [2, 5] */
  get isContainerOpen() {
    return (
      (this.state.isOpen || this.props.isOpen) &&
      !this.props.disabled &&
      (!this.useNativePicker() || this.props.usePickerOnMobile)
    )
  }
 
  render() {
    const {
      label,
      error,
      help,
      use24hr,
      showSeconds,
      overlay,
      ...props
    } = this.props
    const nativeClass = this.useNativePicker()
      ? 'rev-TimePicker--native'
      : 'rev-TimePicker--custom'
    const timeInputProps = omit(props, 'isOpen')
 
    return (
      <label
        className={`rev-TimePicker rev-InputLabel ${nativeClass}`}
        onMouseOver={this.mouseIn.bind(this)}
        onMouseOut={this.mouseOut.bind(this)}
        onFocus={this.onFocus.bind(this)}
        onBlur={this.onBlur.bind(this)}
      >
        {label}
        <TimeInput
          {...timeInputProps}
          error={error}
          onFocus={this.onFocus.bind(this)}
          onBlur={this.onBlur.bind(this)}
          onChange={this.onChange.bind(this)}
          useGoodTimeInput={this.useGoodTimeInput}
          showSeconds={showSeconds}
          formattedValue={this.state.formattedValue}
          generation={this.state.generation}
          inputRef={(input) => (this.nativeInput = input)}
        />
        <InputHelpText>{help}</InputHelpText>
        <InputErrors>{error}</InputErrors>
        <TimeContainer
          {...props}
          className={
            this.isContainerOpen
              ? 'rev-TimeContainer--open'
              : 'rev-TimeContainer--closed'
          }
          selectedTime={this.state.isoValue}
          updateTime={this.updateTime.bind(this)}
          refocusOnClick={this.refocusOnClick.bind(this)}
          use24hr={use24hr}
          showSeconds={showSeconds}
          overlay={overlay}
        />
      </label>
    )
  }
}
 
TimePicker.propTypes = {
  label: PropTypes.node,
  error: PropTypes.node,
  help: PropTypes.node,
  timeFormat: PropTypes.string,
  use24hr: PropTypes.bool,
  showSeconds: PropTypes.bool,
  isOpen: PropTypes.bool,
  disabled: PropTypes.bool,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  onBlur: PropTypes.func,
  usePickerOnMobile: PropTypes.bool,
  overlay: PropTypes.bool,
}
 
TimePicker.TimeInput = TimeInput
TimePicker.TimeContainer = TimeContainer
export {TimeInput, TimeContainer}
export default TimePicker