<commit_before>/*
  node-http-proxy.js: http proxy for node.js

  Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var util = require('util'),
    http = require('http'),
    https = require('https'),
    events = require('events'),
    maxSockets = 100;

//
// Expose version information through `pkginfo`.
//
require('pkginfo')(module, 'version');

//
// ### Export the relevant objects exposed by `node-http-proxy`
//
var HttpProxy    = exports.HttpProxy    = require('./node-http-proxy/http-proxy').HttpProxy,
    ProxyTable   = exports.ProxyTable   = require('./node-http-proxy/proxy-table').ProxyTable,
    RoutingProxy = exports.RoutingProxy = require('./node-http-proxy/routing-proxy').RoutingProxy;

//
// ### function createServer ([port, host, options, handler])
// #### @port {number} **Optional** Port to use on the proxy target host.
// #### @host {string} **Optional** Host of the proxy target.
// #### @options {Object} **Optional** Options for the HttpProxy instance used
// #### @handler {function} **Optional** Request handler for the server
// Returns a server that manages an instance of HttpProxy. Flexible arguments allow for:
//
// * `httpProxy.createServer(9000, 'localhost')`
// * `httpProxy.createServer(9000, 'localhost', options)
// * `httpPRoxy.createServer(function (req, res, proxy) { ... })`
//
exports.createServer = function () {
  var args = Array.prototype.slice.call(arguments),
      handlers = [],
      callback,
      options = {},
      message,
      handler,
      server,
      proxy,
      host,
      port;

  //
  // Liberally parse arguments of the form:
  //
  //    httpProxy.createServer('localhost', 9000, callback);
  //    httpProxy.createServer({ host: 'localhost', port: 9000 }, callback);
  //    **NEED MORE HERE!!!**
  //
  args.forEach(function (arg) {
    arg = Number(arg) || arg;
    switch (typeof arg) {
      case 'string':   host = arg; break;
      case 'number':   port = arg; break;
      case 'object':   options = arg || {}; break;
      case 'function': callback = arg; handlers.push(callback); break;
    };
  });

  //
  // Helper function to create intelligent error message(s)
  // for the very liberal arguments parsing performed by
  // `require('http-proxy').createServer()`.
  //
  function validArguments() {
    var conditions = {
      'port and host': function () {
        return port && host;
      },
      'options.target or options.router': function () {
        return options && (options.router ||
          (options.target && options.target.host && options.target.port));
      },
      'or proxy handlers': function () {
        return handlers && handlers.length;
      }
    }

    var missing = Object.keys(conditions).filter(function (name) {
      return !conditions[name]();
    });

    if (missing.length === 3) {
      message = 'Cannot proxy without ' + missing.join(', ');
      return false;
    }

    return true;
  }

  if (!validArguments()) {
    //
    // If `host`, `port` and `options` are all not passed (with valid
    // options) then this server is improperly configured.
    //
    throw new Error(message);
    return;
  }

  //
  // Hoist up any explicit `host` or `port` arguments
  // that have been passed in to the options we will
  // pass to the `httpProxy.HttpProxy` constructor.
  //
  options.target      = options.target      || {};
  options.target.port = options.target.port || port;
  options.target.host = options.target.host || host;

  if (options.target && options.target.host && options.target.port) {
    //
    // If an explicit `host` and `port` combination has been passed
    // to `.createServer()` then instantiate a hot-path optimized
    // `HttpProxy` object and add the "proxy" middleware layer.
    //
    proxy = new HttpProxy(options);
    handlers.push(function (req, res) {
      proxy.proxyRequest(req, res);
    });
  }
  else {
    //
    // If no explicit `host` or `port` combination has been passed then
    // we have to assume that this is a "go-anywhere" Proxy (i.e. a `RoutingProxy`).
    //
    proxy = new RoutingProxy(options);

    if (options.router) {
      //
      // If a routing table has been supplied than we assume
      // the user intends us to add the "proxy" middleware layer
      // for them
      //
      handlers.push(function (req, res) {
        proxy.proxyRequest(req, res);
      });

      proxy.on('routes', function (routes) {
        server.emit('routes', routes);
      });
    }
  }

  //
  // Create the `http[s].Server` instance which will use
  // an instance of `httpProxy.HttpProxy`.
  //
  handler = handlers.length > 1
    ? exports.stack(handlers, proxy)
    : function (req, res) { handlers[0](req, res, proxy) };

  server  = options.https
    ? https.createServer(options.https, handler)
    : http.createServer(handler);

  server.on('close', function () {
    proxy.close();
  });

  if (!callback) {
    //
    // If an explicit callback has not been supplied then
    // automagically proxy the request using the `HttpProxy`
    // instance we have created.
    //
    server.on('upgrade', function (req, socket, head) {
      proxy.proxyWebSocketRequest(req, socket, head);
    });
  }

  //
  // Set the proxy on the server so it is available
  // to the consumer of the server
  //
  server.proxy = proxy;
  return server;
};

//
// ### function buffer (obj)
// #### @obj {Object} Object to pause events from
// Buffer `data` and `end` events from the given `obj`.
// Consumers of HttpProxy performing async tasks
// __must__ utilize this utility, to re-emit data once
// the async operation has completed, otherwise these
// __events will be lost.__
//
//      var buffer = httpProxy.buffer(req);
//      fs.readFile(path, function () {
//         httpProxy.proxyRequest(req, res, host, port, buffer);
//      });
//
// __Attribution:__ This approach is based heavily on
// [Connect](https://github.com/senchalabs/connect/blob/master/lib/utils.js#L157).
// However, this is not a big leap from the implementation in node-http-proxy < 0.4.0.
// This simply chooses to manage the scope of the events on a new Object literal as opposed to
// [on the HttpProxy instance](https://github.com/nodejitsu/node-http-proxy/blob/v0.3.1/lib/node-http-proxy.js#L154).
//
exports.buffer = function (obj) {
  var events = [],
      onData,
      onEnd;

  obj.on('data', onData = function (data, encoding) {
    events.push(['data', data, encoding]);
  });

  obj.on('end', onEnd = function (data, encoding) {
    events.push(['end', data, encoding]);
  });

  return {
    end: function () {
      obj.removeListener('data', onData);
      obj.removeListener('end', onEnd);
    },
    destroy: function () {
      this.end();
     	this.resume = function () {
     	  console.error("Cannot resume buffer after destroying it.");
     	};

     	onData = onEnd = events = obj = null;
    },
    resume: function () {
      this.end();
      for (var i = 0, len = events.length; i < len; ++i) {
        obj.emit.apply(obj, events[i]);
      }
    }
  };
};

//
// ### function getMaxSockets ()
// Returns the maximum number of sockets
// allowed on __every__ outgoing request
// made by __all__ instances of `HttpProxy`
//
exports.getMaxSockets = function () {
  return maxSockets;
};

//
// ### function setMaxSockets ()
// Sets the maximum number of sockets
// allowed on __every__ outgoing request
// made by __all__ instances of `HttpProxy`
//
exports.setMaxSockets = function (value) {
  maxSockets = value;
};

//
// ### function stack (middlewares, proxy)
// #### @middlewares {Array} Array of functions to stack.
// #### @proxy {HttpProxy|RoutingProxy} Proxy instance to
// Iteratively build up a single handler to the `http.Server`
// `request` event (i.e. `function (req, res)`) by wrapping
// each middleware `layer` into a `child` middleware which
// is in invoked by the parent (i.e. predecessor in the Array).
//
// adapted from https://github.com/creationix/stack
//
exports.stack = function stack (middlewares, proxy) {
  var handle;
  middlewares.reverse().forEach(function (layer) {
    var child = handle;
    handle = function (req, res) {
      var next = function (err) {
        if (err) {
          if (res._headerSent) {
            res.destroy();
          }
          else {
            res.statusCode = 500;
            res.setHeader('Content-Type', 'text/plain');
            res.end('Internal Server Error');
          }

          console.error('Error in middleware(s): %s', err.stack);
          return;
        }

        if (child) {
          child(req, res);
        }
      };

      //
      // Set the prototype of the `next` function to the instance
      // of the `proxy` so that in can be used interchangably from
      // a `connect` style callback and a true `HttpProxy` object.
      //
      // e.g. `function (req, res, next)` vs. `function (req, res, proxy)`
      //
      next.__proto__ = proxy;
      layer(req, res, next);
    };
  });

  return handle;
};

//
// ### function _getAgent (host, port, secure)
// #### @options {Object} Options to use when creating the agent.
//
//    {
//      host: 'localhost',
//      port: 9000,
//      https: true,
//      maxSockets: 100
//    }
//
// Createsan agent from the `http` or `https` module
// and sets the `maxSockets` property appropriately.
//
exports._getAgent = function _getAgent (options) {
  if (!options || !options.host) {
    throw new Error('`options.host` is required to create an Agent.');
  }

  if (!options.port) {
    options.port = options.https ? 443 : 80;
  }

  var Agent = options.https ? https.Agent : http.Agent,
      agent;

  // require('http-proxy').setMaxSockets() should override http's default
  // configuration value (which is pretty low).
  options.maxSockets = options.maxSockets || maxSockets;
  agent = new Agent(options);

  return agent;
}

//
// ### function _getProtocol (options)
// #### @options {Object} Options for the proxy target.
// Returns the appropriate node.js core protocol module (i.e. `http` or `https`)
// based on the `options` supplied.
//
exports._getProtocol = function _getProtocol (options) {
  return options.https ? https : http;
};

//
// ### function _getBase (options)
// #### @options {Object} Options for the proxy target.
// Returns the relevate base object to create on outgoing proxy request.
// If `options.https` are supplied, this function respond with an object
// containing the relevant `ca`, `key`, and `cert` properties.
//
exports._getBase = function _getBase (options) {
  var result = function () {};

  if (options.https && typeof options.https === 'object') {
    ['ca', 'cert', 'key'].forEach(function (key) {
      if (options.https[key]) {
        result.prototype[key] = options.https[key];
      }
    });
  }

  return result;
};
<commit_msg>Emit middlewareError when on middleware error.<commit_after>/*
  node-http-proxy.js: http proxy for node.js

  Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var util = require('util'),
    http = require('http'),
    https = require('https'),
    events = require('events'),
    maxSockets = 100;

//
// Expose version information through `pkginfo`.
//
require('pkginfo')(module, 'version');

//
// ### Export the relevant objects exposed by `node-http-proxy`
//
var HttpProxy    = exports.HttpProxy    = require('./node-http-proxy/http-proxy').HttpProxy,
    ProxyTable   = exports.ProxyTable   = require('./node-http-proxy/proxy-table').ProxyTable,
    RoutingProxy = exports.RoutingProxy = require('./node-http-proxy/routing-proxy').RoutingProxy;

//
// ### function createServer ([port, host, options, handler])
// #### @port {number} **Optional** Port to use on the proxy target host.
// #### @host {string} **Optional** Host of the proxy target.
// #### @options {Object} **Optional** Options for the HttpProxy instance used
// #### @handler {function} **Optional** Request handler for the server
// Returns a server that manages an instance of HttpProxy. Flexible arguments allow for:
//
// * `httpProxy.createServer(9000, 'localhost')`
// * `httpProxy.createServer(9000, 'localhost', options)
// * `httpPRoxy.createServer(function (req, res, proxy) { ... })`
//
exports.createServer = function () {
  var args = Array.prototype.slice.call(arguments),
      handlers = [],
      callback,
      options = {},
      message,
      handler,
      server,
      proxy,
      host,
      port;

  //
  // Liberally parse arguments of the form:
  //
  //    httpProxy.createServer('localhost', 9000, callback);
  //    httpProxy.createServer({ host: 'localhost', port: 9000 }, callback);
  //    **NEED MORE HERE!!!**
  //
  args.forEach(function (arg) {
    arg = Number(arg) || arg;
    switch (typeof arg) {
      case 'string':   host = arg; break;
      case 'number':   port = arg; break;
      case 'object':   options = arg || {}; break;
      case 'function': callback = arg; handlers.push(callback); break;
    };
  });

  //
  // Helper function to create intelligent error message(s)
  // for the very liberal arguments parsing performed by
  // `require('http-proxy').createServer()`.
  //
  function validArguments() {
    var conditions = {
      'port and host': function () {
        return port && host;
      },
      'options.target or options.router': function () {
        return options && (options.router ||
          (options.target && options.target.host && options.target.port));
      },
      'or proxy handlers': function () {
        return handlers && handlers.length;
      }
    }

    var missing = Object.keys(conditions).filter(function (name) {
      return !conditions[name]();
    });

    if (missing.length === 3) {
      message = 'Cannot proxy without ' + missing.join(', ');
      return false;
    }

    return true;
  }

  if (!validArguments()) {
    //
    // If `host`, `port` and `options` are all not passed (with valid
    // options) then this server is improperly configured.
    //
    throw new Error(message);
    return;
  }

  //
  // Hoist up any explicit `host` or `port` arguments
  // that have been passed in to the options we will
  // pass to the `httpProxy.HttpProxy` constructor.
  //
  options.target      = options.target      || {};
  options.target.port = options.target.port || port;
  options.target.host = options.target.host || host;

  if (options.target && options.target.host && options.target.port) {
    //
    // If an explicit `host` and `port` combination has been passed
    // to `.createServer()` then instantiate a hot-path optimized
    // `HttpProxy` object and add the "proxy" middleware layer.
    //
    proxy = new HttpProxy(options);
    handlers.push(function (req, res) {
      proxy.proxyRequest(req, res);
    });
  }
  else {
    //
    // If no explicit `host` or `port` combination has been passed then
    // we have to assume that this is a "go-anywhere" Proxy (i.e. a `RoutingProxy`).
    //
    proxy = new RoutingProxy(options);

    if (options.router) {
      //
      // If a routing table has been supplied than we assume
      // the user intends us to add the "proxy" middleware layer
      // for them
      //
      handlers.push(function (req, res) {
        proxy.proxyRequest(req, res);
      });

      proxy.on('routes', function (routes) {
        server.emit('routes', routes);
      });
    }
  }

  //
  // Create the `http[s].Server` instance which will use
  // an instance of `httpProxy.HttpProxy`.
  //
  handler = handlers.length > 1
    ? exports.stack(handlers, proxy)
    : function (req, res) { handlers[0](req, res, proxy) };

  server  = options.https
    ? https.createServer(options.https, handler)
    : http.createServer(handler);

  server.on('close', function () {
    proxy.close();
  });

  if (!callback) {
    //
    // If an explicit callback has not been supplied then
    // automagically proxy the request using the `HttpProxy`
    // instance we have created.
    //
    server.on('upgrade', function (req, socket, head) {
      proxy.proxyWebSocketRequest(req, socket, head);
    });
  }

  //
  // Set the proxy on the server so it is available
  // to the consumer of the server
  //
  server.proxy = proxy;
  return server;
};

//
// ### function buffer (obj)
// #### @obj {Object} Object to pause events from
// Buffer `data` and `end` events from the given `obj`.
// Consumers of HttpProxy performing async tasks
// __must__ utilize this utility, to re-emit data once
// the async operation has completed, otherwise these
// __events will be lost.__
//
//      var buffer = httpProxy.buffer(req);
//      fs.readFile(path, function () {
//         httpProxy.proxyRequest(req, res, host, port, buffer);
//      });
//
// __Attribution:__ This approach is based heavily on
// [Connect](https://github.com/senchalabs/connect/blob/master/lib/utils.js#L157).
// However, this is not a big leap from the implementation in node-http-proxy < 0.4.0.
// This simply chooses to manage the scope of the events on a new Object literal as opposed to
// [on the HttpProxy instance](https://github.com/nodejitsu/node-http-proxy/blob/v0.3.1/lib/node-http-proxy.js#L154).
//
exports.buffer = function (obj) {
  var events = [],
      onData,
      onEnd;

  obj.on('data', onData = function (data, encoding) {
    events.push(['data', data, encoding]);
  });

  obj.on('end', onEnd = function (data, encoding) {
    events.push(['end', data, encoding]);
  });

  return {
    end: function () {
      obj.removeListener('data', onData);
      obj.removeListener('end', onEnd);
    },
    destroy: function () {
      this.end();
     	this.resume = function () {
     	  console.error("Cannot resume buffer after destroying it.");
     	};

     	onData = onEnd = events = obj = null;
    },
    resume: function () {
      this.end();
      for (var i = 0, len = events.length; i < len; ++i) {
        obj.emit.apply(obj, events[i]);
      }
    }
  };
};

//
// ### function getMaxSockets ()
// Returns the maximum number of sockets
// allowed on __every__ outgoing request
// made by __all__ instances of `HttpProxy`
//
exports.getMaxSockets = function () {
  return maxSockets;
};

//
// ### function setMaxSockets ()
// Sets the maximum number of sockets
// allowed on __every__ outgoing request
// made by __all__ instances of `HttpProxy`
//
exports.setMaxSockets = function (value) {
  maxSockets = value;
};

//
// ### function stack (middlewares, proxy)
// #### @middlewares {Array} Array of functions to stack.
// #### @proxy {HttpProxy|RoutingProxy} Proxy instance to
// Iteratively build up a single handler to the `http.Server`
// `request` event (i.e. `function (req, res)`) by wrapping
// each middleware `layer` into a `child` middleware which
// is in invoked by the parent (i.e. predecessor in the Array).
//
// adapted from https://github.com/creationix/stack
//
exports.stack = function stack (middlewares, proxy) {
  var handle;
  middlewares.reverse().forEach(function (layer) {
    var child = handle;
    handle = function (req, res) {
      var next = function (err) {
        if (err) {
          if (! proxy.emit('middlewareError', err, res, req)) {
            console.error('Error in middleware(s): %s', err.stack);
          }

          if (res._headerSent) {
            res.destroy();
          }
          else {
            res.statusCode = 500;
            res.setHeader('Content-Type', 'text/plain');
            res.end('Internal Server Error');
          }

          return;
        }

        if (child) {
          child(req, res);
        }
      };

      //
      // Set the prototype of the `next` function to the instance
      // of the `proxy` so that in can be used interchangably from
      // a `connect` style callback and a true `HttpProxy` object.
      //
      // e.g. `function (req, res, next)` vs. `function (req, res, proxy)`
      //
      next.__proto__ = proxy;
      layer(req, res, next);
    };
  });

  return handle;
};

//
// ### function _getAgent (host, port, secure)
// #### @options {Object} Options to use when creating the agent.
//
//    {
//      host: 'localhost',
//      port: 9000,
//      https: true,
//      maxSockets: 100
//    }
//
// Createsan agent from the `http` or `https` module
// and sets the `maxSockets` property appropriately.
//
exports._getAgent = function _getAgent (options) {
  if (!options || !options.host) {
    throw new Error('`options.host` is required to create an Agent.');
  }

  if (!options.port) {
    options.port = options.https ? 443 : 80;
  }

  var Agent = options.https ? https.Agent : http.Agent,
      agent;

  // require('http-proxy').setMaxSockets() should override http's default
  // configuration value (which is pretty low).
  options.maxSockets = options.maxSockets || maxSockets;
  agent = new Agent(options);

  return agent;
}

//
// ### function _getProtocol (options)
// #### @options {Object} Options for the proxy target.
// Returns the appropriate node.js core protocol module (i.e. `http` or `https`)
// based on the `options` supplied.
//
exports._getProtocol = function _getProtocol (options) {
  return options.https ? https : http;
};

//
// ### function _getBase (options)
// #### @options {Object} Options for the proxy target.
// Returns the relevate base object to create on outgoing proxy request.
// If `options.https` are supplied, this function respond with an object
// containing the relevant `ca`, `key`, and `cert` properties.
//
exports._getBase = function _getBase (options) {
  var result = function () {};

  if (options.https && typeof options.https === 'object') {
    ['ca', 'cert', 'key'].forEach(function (key) {
      if (options.https[key]) {
        result.prototype[key] = options.https[key];
      }
    });
  }

  return result;
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import DayPicker from './DayPicker';
import { isSameMonth, isDate } from './DateUtils';
import { getModifiersForDay } from './ModifiersUtils';
import { ESC, TAB } from './keys';

// When clicking on a day cell, overlay will be hidden after this timeout
export const HIDE_TIMEOUT = 100;

/**
 * The default component used as Overlay.
 *
 * @param {Object} props
 */
export function OverlayComponent({
  input,
  selectedDay,
  month,
  children,
  classNames,
  ...props
}) {
  return (

{children}

  );
}

OverlayComponent.propTypes = {
  input: PropTypes.any,
  selectedDay: PropTypes.any,
  month: PropTypes.instanceOf(Date),
  children: PropTypes.node,
  classNames: PropTypes.object,
};

/**
 * The default function used to format a Date to String, passed to the `format`
 * prop.
 * @param {Date} d
 * @return {String}
 */
export function defaultFormat(d) {
  if (isDate(d)) {
    const year = d.getFullYear();
    const month = `${d.getMonth() + 1}`;
    const day = `${d.getDate()}`;
    return `${year}-${month}-${day}`;
  }
  return '';
}

/**
 * The default function used to parse a String as Date, passed to the `parse`
 * prop.
 * @param {String} str
 * @return {Date}
 */
export function defaultParse(str) {
  if (typeof str !== 'string') {
    return undefined;
  }
  const split = str.split('-');
  if (split.length !== 3) {
    return undefined;
  }
  const year = parseInt(split[0], 10);
  const month = parseInt(split[1], 10) - 1;
  const day = parseInt(split[2], 10);
  if (
    isNaN(year) ||
    String(year).length > 4 ||
    isNaN(month) ||
    isNaN(day) ||
    day <= 0 ||
    day > 31 ||
    month < 0 ||
    month >= 12
  ) {
    return undefined;
  }

  return new Date(year, month, day);
}

export default class DayPickerInput extends React.Component {
  static propTypes = {
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]),
    inputProps: PropTypes.object,
    placeholder: PropTypes.string,

    format: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.arrayOf(PropTypes.string),
    ]),

    formatDate: PropTypes.func,
    parseDate: PropTypes.func,

    showOverlay: PropTypes.bool,
    dayPickerProps: PropTypes.object,
    hideOnDayClick: PropTypes.bool,
    clickUnselectsDay: PropTypes.bool,
    keepFocus: PropTypes.bool,
    component: PropTypes.any,
    overlayComponent: PropTypes.any,

    classNames: PropTypes.shape({
      container: PropTypes.string,
      overlayWrapper: PropTypes.string,
      overlay: PropTypes.string.isRequired,
    }),

    onDayChange: PropTypes.func,
    onChange: PropTypes.func,
    onClick: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onKeyUp: PropTypes.func,
  };

  static defaultProps = {
    dayPickerProps: {},
    value: '',
    placeholder: 'YYYY-M-D',
    format: 'L',
    formatDate: defaultFormat,
    parseDate: defaultParse,
    showOverlay: false,
    hideOnDayClick: true,
    clickUnselectsDay: false,
    keepFocus: true,
    component: 'input',
    inputProps: {},
    overlayComponent: OverlayComponent,
    classNames: {
      container: 'DayPickerInput',
      overlayWrapper: 'DayPickerInput-OverlayWrapper',
      overlay: 'DayPickerInput-Overlay',
    },
  };

  constructor(props) {
    super(props);

    this.state = this.getInitialStateFromProps(props);
    this.state.showOverlay = props.showOverlay;

    this.hideAfterDayClick = this.hideAfterDayClick.bind(this);
    this.handleInputClick = this.handleInputClick.bind(this);
    this.handleInputFocus = this.handleInputFocus.bind(this);
    this.handleInputBlur = this.handleInputBlur.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInputKeyDown = this.handleInputKeyDown.bind(this);
    this.handleInputKeyUp = this.handleInputKeyUp.bind(this);
    this.handleDayClick = this.handleDayClick.bind(this);
    this.handleMonthChange = this.handleMonthChange.bind(this);
    this.handleOverlayFocus = this.handleOverlayFocus.bind(this);
    this.handleOverlayBlur = this.handleOverlayBlur.bind(this);
  }

  componentDidUpdate(prevProps) {
    const newState = {};

    // Current props
    const { value, formatDate, format, dayPickerProps } = this.props;

    // Update the input value if the `value` prop has changed
    if (value !== prevProps.value) {
      if (isDate(value)) {
        newState.value = formatDate(value, format, dayPickerProps.locale);
      } else {
        newState.value = value;
      }
    }

    // Update the month if the months from props changed
    const prevMonth = prevProps.dayPickerProps.month;
    if (
      dayPickerProps.month &&
      dayPickerProps.month !== prevMonth &&
      !isSameMonth(dayPickerProps.month, prevMonth)
    ) {
      newState.month = dayPickerProps.month;
    }

    // Updated the selected days from props if they changed
    if (prevProps.dayPickerProps.selectedDays !== dayPickerProps.selectedDays) {
      newState.selectedDays = dayPickerProps.selectedDays;
    }

    if (Object.keys(newState).length > 0) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState(newState);
    }
  }

  componentWillUnmount() {
    clearTimeout(this.clickTimeout);
    clearTimeout(this.hideTimeout);
    clearTimeout(this.inputFocusTimeout);
    clearTimeout(this.inputBlurTimeout);
    clearTimeout(this.overlayBlurTimeout);
  }

  getInitialMonthFromProps(props) {
    const { dayPickerProps, format } = props;
    let day;
    if (props.value) {
      if (isDate(props.value)) {
        day = props.value;
      } else {
        day = props.parseDate(props.value, format, dayPickerProps.locale);
      }
    }
    return (
      dayPickerProps.initialMonth || dayPickerProps.month || day || new Date()
    );
  }

  getInitialStateFromProps(props) {
    const { dayPickerProps, formatDate, format } = props;
    let { value } = props;
    if (props.value && isDate(props.value)) {
      value = formatDate(props.value, format, dayPickerProps.locale);
    }
    return {
      value,
      month: this.getInitialMonthFromProps(props),
      selectedDays: dayPickerProps.selectedDays,
    };
  }

  getInput() {
    return this.input;
  }

  getDayPicker() {
    return this.daypicker;
  }

  input = null;
  daypicker = null;
  clickTimeout = null;
  hideTimeout = null;
  inputBlurTimeout = null;
  inputFocusTimeout = null;

  /**
   * Update the component's state and fire the `onDayChange` event passing the
   * day's modifiers to it.
   *
   * @param {Date} day - Will be used for changing the month
   * @param {String} value - Input field value
   * @private
   */
  updateState(day, value, callback) {
    const { dayPickerProps, onDayChange } = this.props;
    this.setState({ month: day, value }, () => {
      if (callback) {
        callback();
      }
      if (!onDayChange) {
        return;
      }
      const modifiersObj = {
        disabled: dayPickerProps.disabledDays,
        selected: dayPickerProps.selectedDays,
        ...dayPickerProps.modifiers,
      };
      const modifiers = getModifiersForDay(day, modifiersObj).reduce(
        (obj, modifier) => {
          const newObj = { ...obj };
          newObj[modifier] = true;
          return newObj;
        },
        {}
      );
      onDayChange(day, modifiers);
    });
  }

  /**
   * Show the Day Picker overlay.
   *
   * @memberof DayPickerInput
   */
  showDayPicker() {
    const { parseDate, format, dayPickerProps } = this.props;
    const { value, showOverlay } = this.state;
    if (showOverlay) {
      return;
    }
    // Reset the current displayed month when showing the overlay
    const month = value
      ? parseDate(value, format, dayPickerProps.locale) // Use the month in the input field
      : this.getInitialMonthFromProps(this.props); // Restore the month from the props
    this.setState({
      showOverlay: true,
      month: month || this.state.month,
    });
  }

  /**
   * Hide the Day Picker overlay
   *
   * @memberof DayPickerInput
   */
  hideDayPicker() {
    if (this.state.showOverlay === false) {
      return;
    }
    this.setState({ showOverlay: false });
  }

  hideAfterDayClick() {
    if (!this.props.hideOnDayClick) {
      return;
    }
    this.hideTimeout = setTimeout(() => this.hideDayPicker(), HIDE_TIMEOUT);
  }

  handleInputClick(e) {
    this.showDayPicker();
    if (this.props.inputProps.onClick) {
      e.persist();
      this.props.inputProps.onClick(e);
    }
  }

  handleInputFocus(e) {
    this.showDayPicker();
    // Set `overlayHasFocus` after a timeout so the overlay can be hidden when
    // the input is blurred
    this.inputFocusTimeout = setTimeout(() => {
      this.overlayHasFocus = false;
    }, 2);
    if (this.props.inputProps.onFocus) {
      e.persist();
      this.props.inputProps.onFocus(e);
    }
  }

  // When the input is blurred, the overlay should disappear. However the input
  // is blurred also when the user interacts with the overlay (e.g. the overlay
  // get the focus by clicking it). In these cases, the overlay should not be
  // hidden. There are different approaches to avoid hiding the overlay when
  // this happens, but the only cross-browser hack we’ve found is to set all
  // these timeouts in code before changing `overlayHasFocus`.
  handleInputBlur(e) {
    this.inputBlurTimeout = setTimeout(() => {
      if (!this.overlayHasFocus) {
        this.hideDayPicker();
      }
    }, 1);
    if (this.props.inputProps.onBlur) {
      e.persist();
      this.props.inputProps.onBlur(e);
    }
  }

  handleOverlayFocus(e) {
    e.preventDefault();
    this.overlayHasFocus = true;
    if (
      !this.props.keepFocus ||
      !this.input ||
      typeof this.input.focus !== 'function'
    ) {
      return;
    }
    this.input.focus();
  }

  handleOverlayBlur() {
    // We need to set a timeout otherwise IE11 will hide the overlay when
    // focusing it
    this.overlayBlurTimeout = setTimeout(() => {
      this.overlayHasFocus = false;
    }, 3);
  }

  handleInputChange(e) {
    const {
      dayPickerProps,
      format,
      inputProps,
      onDayChange,
      parseDate,
    } = this.props;
    if (inputProps.onChange) {
      e.persist();
      inputProps.onChange(e);
    }
    const { value } = e.target;
    if (value.trim() === '') {
      this.setState({ value });
      if (onDayChange) onDayChange(undefined, {});
      return;
    }
    const day = parseDate(value, format, dayPickerProps.locale);
    if (!day) {
      this.setState({ value });
      if (onDayChange) onDayChange(undefined, {});
      return;
    }
    this.updateState(day, value);
  }

  handleInputKeyDown(e) {
    if (e.keyCode === TAB) {
      this.hideDayPicker();
    } else {
      this.showDayPicker();
    }
    if (this.props.inputProps.onKeyDown) {
      e.persist();
      this.props.inputProps.onKeyDown(e);
    }
  }

  handleInputKeyUp(e) {
    if (e.keyCode === ESC) {
      this.hideDayPicker();
    } else {
      this.showDayPicker();
    }
    if (this.props.inputProps.onKeyUp) {
      e.persist();
      this.props.inputProps.onKeyUp(e);
    }
  }

  handleMonthChange(month) {
    this.setState({ month }, () => {
      if (
        this.props.dayPickerProps &&
        this.props.dayPickerProps.onMonthChange
      ) {
        this.props.dayPickerProps.onMonthChange(month);
      }
    });
  }

  handleDayClick(day, modifiers, e) {
    const {
      clickUnselectsDay,
      dayPickerProps,
      onDayChange,
      formatDate,
      format,
    } = this.props;
    if (dayPickerProps.onDayClick) {
      dayPickerProps.onDayClick(day, modifiers, e);
    }

    // Do nothing if the day is disabled
    if (
      modifiers.disabled ||
      (dayPickerProps &&
        dayPickerProps.classNames &&
        modifiers[dayPickerProps.classNames.disabled])
    ) {
      return;
    }

    // If the clicked day is already selected, remove the clicked day
    // from the selected days and empty the field value
    if (modifiers.selected && clickUnselectsDay) {
      let { selectedDays } = this.state;
      if (Array.isArray(selectedDays)) {
        selectedDays = selectedDays.slice(0);
        const selectedDayIdx = selectedDays.indexOf(day);
        selectedDays.splice(selectedDayIdx, 1);
      } else if (selectedDays) {
        selectedDays = null;
      }
      this.setState({ value: '', selectedDays }, this.hideAfterDayClick);
      if (onDayChange) {
        onDayChange(undefined, modifiers);
      }
      return;
    }

    const value = formatDate(day, format, dayPickerProps.locale);
    this.setState({ value, month: day }, () => {
      if (onDayChange) {
        onDayChange(day, modifiers);
      }
      this.hideAfterDayClick();
    });
  }

  renderOverlay() {
    const {
      classNames,
      dayPickerProps,
      parseDate,
      formatDate,
      format,
    } = this.props;
    const { selectedDays, value } = this.state;
    let selectedDay;
    if (!selectedDays && value) {
      const day = parseDate(value, format, dayPickerProps.locale);
      if (day) {
        selectedDay = day;
      }
    } else if (selectedDays) {
      selectedDay = selectedDays;
    }
    let onTodayButtonClick;
    if (dayPickerProps.todayButton) {
      // Set the current day when clicking the today button
      onTodayButtonClick = () =>
        this.updateState(
          new Date(),
          formatDate(new Date(), format, dayPickerProps.locale),
          this.hideAfterDayClick
        );
    }
    const Overlay = this.props.overlayComponent;
    return (
      <Overlay
        classNames={classNames}
        month={this.state.month}
        selectedDay={selectedDay}
        input={this.input}
        tabIndex={0} // tabIndex is necessary to catch focus/blur events on Safari
        onFocus={this.handleOverlayFocus}
        onBlur={this.handleOverlayBlur}
      >
        <DayPicker
          ref={el => (this.daypicker = el)}
          onTodayButtonClick={onTodayButtonClick}
          {...dayPickerProps}
          month={this.state.month}
          selectedDays={selectedDay}
          onDayClick={this.handleDayClick}
          onMonthChange={this.handleMonthChange}
        />
      </Overlay>
    );
  }

  render() {
    const Input = this.props.component;
    const { inputProps } = this.props;
    return (

        <Input
          ref={el => (this.input = el)}
          placeholder={this.props.placeholder}
          {...inputProps}
          value={this.state.value}
          onChange={this.handleInputChange}
          onFocus={this.handleInputFocus}
          onBlur={this.handleInputBlur}
          onKeyDown={this.handleInputKeyDown}
          onKeyUp={this.handleInputKeyUp}
          onClick={!inputProps.disabled ? this.handleInputClick : undefined}
        />
        {this.state.showOverlay && this.renderOverlay()}

    );
  }
}
<commit_msg>Simplify modifier reduce function<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import DayPicker from './DayPicker';
import { isSameMonth, isDate } from './DateUtils';
import { getModifiersForDay } from './ModifiersUtils';
import { ESC, TAB } from './keys';

// When clicking on a day cell, overlay will be hidden after this timeout
export const HIDE_TIMEOUT = 100;

/**
 * The default component used as Overlay.
 *
 * @param {Object} props
 */
export function OverlayComponent({
  input,
  selectedDay,
  month,
  children,
  classNames,
  ...props
}) {
  return (

{children}

  );
}

OverlayComponent.propTypes = {
  input: PropTypes.any,
  selectedDay: PropTypes.any,
  month: PropTypes.instanceOf(Date),
  children: PropTypes.node,
  classNames: PropTypes.object,
};

/**
 * The default function used to format a Date to String, passed to the `format`
 * prop.
 * @param {Date} d
 * @return {String}
 */
export function defaultFormat(d) {
  if (isDate(d)) {
    const year = d.getFullYear();
    const month = `${d.getMonth() + 1}`;
    const day = `${d.getDate()}`;
    return `${year}-${month}-${day}`;
  }
  return '';
}

/**
 * The default function used to parse a String as Date, passed to the `parse`
 * prop.
 * @param {String} str
 * @return {Date}
 */
export function defaultParse(str) {
  if (typeof str !== 'string') {
    return undefined;
  }
  const split = str.split('-');
  if (split.length !== 3) {
    return undefined;
  }
  const year = parseInt(split[0], 10);
  const month = parseInt(split[1], 10) - 1;
  const day = parseInt(split[2], 10);
  if (
    isNaN(year) ||
    String(year).length > 4 ||
    isNaN(month) ||
    isNaN(day) ||
    day <= 0 ||
    day > 31 ||
    month < 0 ||
    month >= 12
  ) {
    return undefined;
  }

  return new Date(year, month, day);
}

export default class DayPickerInput extends React.Component {
  static propTypes = {
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]),
    inputProps: PropTypes.object,
    placeholder: PropTypes.string,

    format: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.arrayOf(PropTypes.string),
    ]),

    formatDate: PropTypes.func,
    parseDate: PropTypes.func,

    showOverlay: PropTypes.bool,
    dayPickerProps: PropTypes.object,
    hideOnDayClick: PropTypes.bool,
    clickUnselectsDay: PropTypes.bool,
    keepFocus: PropTypes.bool,
    component: PropTypes.any,
    overlayComponent: PropTypes.any,

    classNames: PropTypes.shape({
      container: PropTypes.string,
      overlayWrapper: PropTypes.string,
      overlay: PropTypes.string.isRequired,
    }),

    onDayChange: PropTypes.func,
    onChange: PropTypes.func,
    onClick: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onKeyUp: PropTypes.func,
  };

  static defaultProps = {
    dayPickerProps: {},
    value: '',
    placeholder: 'YYYY-M-D',
    format: 'L',
    formatDate: defaultFormat,
    parseDate: defaultParse,
    showOverlay: false,
    hideOnDayClick: true,
    clickUnselectsDay: false,
    keepFocus: true,
    component: 'input',
    inputProps: {},
    overlayComponent: OverlayComponent,
    classNames: {
      container: 'DayPickerInput',
      overlayWrapper: 'DayPickerInput-OverlayWrapper',
      overlay: 'DayPickerInput-Overlay',
    },
  };

  constructor(props) {
    super(props);

    this.state = this.getInitialStateFromProps(props);
    this.state.showOverlay = props.showOverlay;

    this.hideAfterDayClick = this.hideAfterDayClick.bind(this);
    this.handleInputClick = this.handleInputClick.bind(this);
    this.handleInputFocus = this.handleInputFocus.bind(this);
    this.handleInputBlur = this.handleInputBlur.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInputKeyDown = this.handleInputKeyDown.bind(this);
    this.handleInputKeyUp = this.handleInputKeyUp.bind(this);
    this.handleDayClick = this.handleDayClick.bind(this);
    this.handleMonthChange = this.handleMonthChange.bind(this);
    this.handleOverlayFocus = this.handleOverlayFocus.bind(this);
    this.handleOverlayBlur = this.handleOverlayBlur.bind(this);
  }

  componentDidUpdate(prevProps) {
    const newState = {};

    // Current props
    const { value, formatDate, format, dayPickerProps } = this.props;

    // Update the input value if the `value` prop has changed
    if (value !== prevProps.value) {
      if (isDate(value)) {
        newState.value = formatDate(value, format, dayPickerProps.locale);
      } else {
        newState.value = value;
      }
    }

    // Update the month if the months from props changed
    const prevMonth = prevProps.dayPickerProps.month;
    if (
      dayPickerProps.month &&
      dayPickerProps.month !== prevMonth &&
      !isSameMonth(dayPickerProps.month, prevMonth)
    ) {
      newState.month = dayPickerProps.month;
    }

    // Updated the selected days from props if they changed
    if (prevProps.dayPickerProps.selectedDays !== dayPickerProps.selectedDays) {
      newState.selectedDays = dayPickerProps.selectedDays;
    }

    if (Object.keys(newState).length > 0) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState(newState);
    }
  }

  componentWillUnmount() {
    clearTimeout(this.clickTimeout);
    clearTimeout(this.hideTimeout);
    clearTimeout(this.inputFocusTimeout);
    clearTimeout(this.inputBlurTimeout);
    clearTimeout(this.overlayBlurTimeout);
  }

  getInitialMonthFromProps(props) {
    const { dayPickerProps, format } = props;
    let day;
    if (props.value) {
      if (isDate(props.value)) {
        day = props.value;
      } else {
        day = props.parseDate(props.value, format, dayPickerProps.locale);
      }
    }
    return (
      dayPickerProps.initialMonth || dayPickerProps.month || day || new Date()
    );
  }

  getInitialStateFromProps(props) {
    const { dayPickerProps, formatDate, format } = props;
    let { value } = props;
    if (props.value && isDate(props.value)) {
      value = formatDate(props.value, format, dayPickerProps.locale);
    }
    return {
      value,
      month: this.getInitialMonthFromProps(props),
      selectedDays: dayPickerProps.selectedDays,
    };
  }

  getInput() {
    return this.input;
  }

  getDayPicker() {
    return this.daypicker;
  }

  input = null;
  daypicker = null;
  clickTimeout = null;
  hideTimeout = null;
  inputBlurTimeout = null;
  inputFocusTimeout = null;

  /**
   * Update the component's state and fire the `onDayChange` event passing the
   * day's modifiers to it.
   *
   * @param {Date} day - Will be used for changing the month
   * @param {String} value - Input field value
   * @private
   */
  updateState(day, value, callback) {
    const { dayPickerProps, onDayChange } = this.props;
    this.setState({ month: day, value }, () => {
      if (callback) {
        callback();
      }
      if (!onDayChange) {
        return;
      }
      const modifiersObj = {
        disabled: dayPickerProps.disabledDays,
        selected: dayPickerProps.selectedDays,
        ...dayPickerProps.modifiers,
      };
      const modifiers = getModifiersForDay(day, modifiersObj).reduce(
        (obj, modifier) => ({
          ...obj,
          [modifier]: true
        }), {}
      );
      onDayChange(day, modifiers);
    });
  }

  /**
   * Show the Day Picker overlay.
   *
   * @memberof DayPickerInput
   */
  showDayPicker() {
    const { parseDate, format, dayPickerProps } = this.props;
    const { value, showOverlay } = this.state;
    if (showOverlay) {
      return;
    }
    // Reset the current displayed month when showing the overlay
    const month = value
      ? parseDate(value, format, dayPickerProps.locale) // Use the month in the input field
      : this.getInitialMonthFromProps(this.props); // Restore the month from the props
    this.setState({
      showOverlay: true,
      month: month || this.state.month,
    });
  }

  /**
   * Hide the Day Picker overlay
   *
   * @memberof DayPickerInput
   */
  hideDayPicker() {
    if (this.state.showOverlay === false) {
      return;
    }
    this.setState({ showOverlay: false });
  }

  hideAfterDayClick() {
    if (!this.props.hideOnDayClick) {
      return;
    }
    this.hideTimeout = setTimeout(() => this.hideDayPicker(), HIDE_TIMEOUT);
  }

  handleInputClick(e) {
    this.showDayPicker();
    if (this.props.inputProps.onClick) {
      e.persist();
      this.props.inputProps.onClick(e);
    }
  }

  handleInputFocus(e) {
    this.showDayPicker();
    // Set `overlayHasFocus` after a timeout so the overlay can be hidden when
    // the input is blurred
    this.inputFocusTimeout = setTimeout(() => {
      this.overlayHasFocus = false;
    }, 2);
    if (this.props.inputProps.onFocus) {
      e.persist();
      this.props.inputProps.onFocus(e);
    }
  }

  // When the input is blurred, the overlay should disappear. However the input
  // is blurred also when the user interacts with the overlay (e.g. the overlay
  // get the focus by clicking it). In these cases, the overlay should not be
  // hidden. There are different approaches to avoid hiding the overlay when
  // this happens, but the only cross-browser hack we’ve found is to set all
  // these timeouts in code before changing `overlayHasFocus`.
  handleInputBlur(e) {
    this.inputBlurTimeout = setTimeout(() => {
      if (!this.overlayHasFocus) {
        this.hideDayPicker();
      }
    }, 1);
    if (this.props.inputProps.onBlur) {
      e.persist();
      this.props.inputProps.onBlur(e);
    }
  }

  handleOverlayFocus(e) {
    e.preventDefault();
    this.overlayHasFocus = true;
    if (
      !this.props.keepFocus ||
      !this.input ||
      typeof this.input.focus !== 'function'
    ) {
      return;
    }
    this.input.focus();
  }

  handleOverlayBlur() {
    // We need to set a timeout otherwise IE11 will hide the overlay when
    // focusing it
    this.overlayBlurTimeout = setTimeout(() => {
      this.overlayHasFocus = false;
    }, 3);
  }

  handleInputChange(e) {
    const {
      dayPickerProps,
      format,
      inputProps,
      onDayChange,
      parseDate,
    } = this.props;
    if (inputProps.onChange) {
      e.persist();
      inputProps.onChange(e);
    }
    const { value } = e.target;
    if (value.trim() === '') {
      this.setState({ value });
      if (onDayChange) onDayChange(undefined, {});
      return;
    }
    const day = parseDate(value, format, dayPickerProps.locale);
    if (!day) {
      this.setState({ value });
      if (onDayChange) onDayChange(undefined, {});
      return;
    }
    this.updateState(day, value);
  }

  handleInputKeyDown(e) {
    if (e.keyCode === TAB) {
      this.hideDayPicker();
    } else {
      this.showDayPicker();
    }
    if (this.props.inputProps.onKeyDown) {
      e.persist();
      this.props.inputProps.onKeyDown(e);
    }
  }

  handleInputKeyUp(e) {
    if (e.keyCode === ESC) {
      this.hideDayPicker();
    } else {
      this.showDayPicker();
    }
    if (this.props.inputProps.onKeyUp) {
      e.persist();
      this.props.inputProps.onKeyUp(e);
    }
  }

  handleMonthChange(month) {
    this.setState({ month }, () => {
      if (
        this.props.dayPickerProps &&
        this.props.dayPickerProps.onMonthChange
      ) {
        this.props.dayPickerProps.onMonthChange(month);
      }
    });
  }

  handleDayClick(day, modifiers, e) {
    const {
      clickUnselectsDay,
      dayPickerProps,
      onDayChange,
      formatDate,
      format,
    } = this.props;
    if (dayPickerProps.onDayClick) {
      dayPickerProps.onDayClick(day, modifiers, e);
    }

    // Do nothing if the day is disabled
    if (
      modifiers.disabled ||
      (dayPickerProps &&
        dayPickerProps.classNames &&
        modifiers[dayPickerProps.classNames.disabled])
    ) {
      return;
    }

    // If the clicked day is already selected, remove the clicked day
    // from the selected days and empty the field value
    if (modifiers.selected && clickUnselectsDay) {
      let { selectedDays } = this.state;
      if (Array.isArray(selectedDays)) {
        selectedDays = selectedDays.slice(0);
        const selectedDayIdx = selectedDays.indexOf(day);
        selectedDays.splice(selectedDayIdx, 1);
      } else if (selectedDays) {
        selectedDays = null;
      }
      this.setState({ value: '', selectedDays }, this.hideAfterDayClick);
      if (onDayChange) {
        onDayChange(undefined, modifiers);
      }
      return;
    }

    const value = formatDate(day, format, dayPickerProps.locale);
    this.setState({ value, month: day }, () => {
      if (onDayChange) {
        onDayChange(day, modifiers);
      }
      this.hideAfterDayClick();
    });
  }

  renderOverlay() {
    const {
      classNames,
      dayPickerProps,
      parseDate,
      formatDate,
      format,
    } = this.props;
    const { selectedDays, value } = this.state;
    let selectedDay;
    if (!selectedDays && value) {
      const day = parseDate(value, format, dayPickerProps.locale);
      if (day) {
        selectedDay = day;
      }
    } else if (selectedDays) {
      selectedDay = selectedDays;
    }
    let onTodayButtonClick;
    if (dayPickerProps.todayButton) {
      // Set the current day when clicking the today button
      onTodayButtonClick = () =>
        this.updateState(
          new Date(),
          formatDate(new Date(), format, dayPickerProps.locale),
          this.hideAfterDayClick
        );
    }
    const Overlay = this.props.overlayComponent;
    return (
      <Overlay
        classNames={classNames}
        month={this.state.month}
        selectedDay={selectedDay}
        input={this.input}
        tabIndex={0} // tabIndex is necessary to catch focus/blur events on Safari
        onFocus={this.handleOverlayFocus}
        onBlur={this.handleOverlayBlur}
      >
        <DayPicker
          ref={el => (this.daypicker = el)}
          onTodayButtonClick={onTodayButtonClick}
          {...dayPickerProps}
          month={this.state.month}
          selectedDays={selectedDay}
          onDayClick={this.handleDayClick}
          onMonthChange={this.handleMonthChange}
        />
      </Overlay>
    );
  }

  render() {
    const Input = this.props.component;
    const { inputProps } = this.props;
    return (

        <Input
          ref={el => (this.input = el)}
          placeholder={this.props.placeholder}
          {...inputProps}
          value={this.state.value}
          onChange={this.handleInputChange}
          onFocus={this.handleInputFocus}
          onBlur={this.handleInputBlur}
          onKeyDown={this.handleInputKeyDown}
          onKeyUp={this.handleInputKeyUp}
          onClick={!inputProps.disabled ? this.handleInputClick : undefined}
        />
        {this.state.showOverlay && this.renderOverlay()}

    );
  }
}
<|endoftext|>


<commit_before>function Groundstation() {
  this.channels = new Channels();
  this.channels.url = '/channels';

  this.active_grefs = new Grefs();

  this.username = localStorage.getItem("airship.committer") || "Anonymous Coward";

  this.renderers = {};
  this.validators = {};
}
function init_airship(groundstation) {
  _.each(groundstation.channels.models, function(channel) {
    new ChannelTab({
      model: channel,
      id: channel.attributes["name"]
    });
  });
  rendered_gref_content = new RenderedGref({
    model: rendered_gref
  });
  // Wire up user switching
  // TODO Currently not stored because I haven't decided where it should live. PRobably git-config(5)

  $("#current-user-name").html(groundstation.username);
  $("#current-user-name").on('click', function() {
    var username = prompt("Username for committing:");
    if (username !== null) {
      groundstation.username = username;
      $("#current-user-name").html(groundstation.username);
      try {
        localStorage.setItem("airship.committer", username);
      } catch (e) {
        console.log("Not setting committer name in localStorage");
      }
    }
  });
  var new_gref = {
    title: $("#new-gref-title").text(),
    body: $("#new-gref-body")[0].value,
    name: $("#new-gref-name").text()
  };
  var new_gref_validator = groundstation.validators.gref(new_gref.name, new_gref.title, new_gref.body);

  $("#new-gref").on('click', function() {
    $("#new-gref-title").text(new_gref.title);
    $("#new-gref-body")[0].value = new_gref.body;
    $("#new-gref-name").text(new_gref.name);
    var modal = $("#new-gref-modal");
    modal.modal();
  });
  $("#new-gref-cancel").on('click', function() {
    $("#new-gref-modal").modal('hide');
  });
  $("#new-gref-create").on('click', function() {
    var title = $("#new-gref-title").text(),
        body = $("#new-gref-body")[0].value,
        name = $("#new-gref-name").text(),
        protocol = $("#new-gref-protocol").text();

    if (new_gref_validator(name, title, body)) {
      $.ajax({
        type: "PUT",
        url: groundstation.active_grefs.url,
        data: {
          title: title,
          body: body,
          name: name,
          protocol: protocol,

          user: groundstation.username

        },
        success: function(data, st, xhr) {
          $("#new-gref-modal").modal('hide');
          groundstation.active_grefs.redraw();
        }
      });
    } else {
      // TODO Actually give the user something to go with
      alert("Validation failed!");
    }
  });
}

var Channel = Backbone.Model.extend();
var Channels = Backbone.Collection.extend({
  model: Channel
});

var Gref = Backbone.Model.extend();
var Grefs = Backbone.Collection.extend({
  model: Gref
});

var GrefMenuItem = Backbone.View.extend({
  tagName: "li",
  className: "gref",

  template: '{{identifier}}',

  getUrl: function() {
    return "/gref/" + this.model.attributes["channel"] + "/" + this.model.attributes["identifier"];
  },

  render: function() {
    this.$el.html(this.template.replace("{{identifier}}", this.model.attributes["identifier"]));
    return this;
  },

  select: function() {
    var active_el = this.el;
    $(this.el.parentElement.children).removeClass("active");
    rendered_gref.url = this.getUrl();
    rendered_gref.fetch({
      success: function(model, response, options) {
        $(active_el).addClass("active");
        rendered_gref_content.render();
      }
    });
  },

  events: {
    "click .select":  "select"
  },

  install: function() {
    $('#current-grefs')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }
});

var visible_grefs = [];
var ChannelTab = Backbone.View.extend({

  tagName: "li",

  className: "",

  template: '{{name}}',

  render: function() {
    this.$el.html(this.template.replace("{{name}}", this.model.attributes["name"]));
    return this;
  },

  select: function() {
    var self = this;
    var current_grefs = $("#current-grefs")[0];
    groundstation.active_grefs.url = '/grefs/' + this.model.attributes["name"];
    groundstation.active_grefs.redraw = function() {
      groundstation.active_grefs.fetch({
        success: function(collection, response, options) {
          $("#active-channel").html(self.model.attributes["name"]);
          $("#gref-container").show();
          _.each(visible_grefs, function(el) { el.remove(); });
          _.each(collection.models, function(gref) {
            visible_grefs.push(new GrefMenuItem({
              model: gref
            }));
          });
        }
      });
    };
    groundstation.active_grefs.redraw();
  },

  events: {
    "click .select":          "select"
  },

  install: function() {
    $('#channels-content')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }

});

function buildCommentBox(div, model) {
  var row, input, span, submit;

  row = document.createElement("div");
  row.className = "input-group";

  input = document.createElement("textarea");
  input.setAttribute('rows', 7);
  input.contentEditable = true;
  input.id = "new-comment-body";

  span = document.createElement("span");
  span.className = "input-group-btn";

  submit = document.createElement("button");
  submit.className = "btn";
  submit.id = "new-comment-submit";
  $(submit).text("Submit");
  span.appendChild(submit);

  row.appendChild(input);
  row.appendChild(span);

  $(submit).on('click', function(ev) {
    $.ajax({
        type: "POST",
        url: model.url,
        data: {
            body: input.value,
            parents: JSON.stringify(model.attributes["tips"]),
            user: groundstation.username

        },
        success: function(data, st, xhr) {
            rendered_gref.fetch();
            console.log("Successfully updated groundstation");
        }
    });
    console.log("Sending new comment to groundstation");
  });

  div.appendChild(row);
}

var RenderedGref = Backbone.View.extend({

  tagName: "div",
  className: "",

  render: function() {
    var self = this;
    var content = this.model.attributes["content"];
    var root = this.model.attributes["root"];
    var renderer = null;

    $(this.$el).children().remove();
    $("#gref-graph").children().remove();

    renderer = (function() {
      for (var renderer in groundstation.renderers) {
        if (groundstation.renderers.hasOwnProperty(renderer)) {
          if (root.protocol.search(renderer) === 0)
            return groundstation.renderers[renderer];
        }
      }
    })();
    if (renderer === null) {
      console.log("Unhandled protocol: " + root.protocol);
      return this;
    }

    // Stick the root object in the DOM to make parent linking sane.
    (function() {
      var el = document.createElement("div");
      el.setAttribute("id", root.hash);
      self.el.appendChild(el);
    })();

    _.each(content, function(item) {
      var el = renderer(item);
      if (el) {
        el.setAttribute("id", item.hash);
        var signature = self.model.attributes.signatures[item.hash];
        if (signature !== undefined) {
          if (signature === false) {
            el.setAttribute("data-invalid-signature", "true");
          } else {
            el.setAttribute("data-signature", signature);
          }
        }
        self.el.appendChild(el);
      }
    });
    buildCommentBox(self.el, self.model);

    var graph_span = $("#gref-graph-span");
    var width  = graph_span.width(),
        height = 500;

    var force = d3.layout.force()
      .charge(-120)
      .size([width, height])
      .linkDistance(30);

    var svg = d3.select("#gref-graph").append("svg")
      .attr("width", width)
      .attr("height", height);;

    var data = this.model.attributes;
    var nodes = data.content;
    data.root.parents = [];
    data.root.fixed = true;
    data.root.x = width / 2;
    data.root.y = 10;
    nodes.push(data.root);

    var hash_to_node = {};
    nodes.forEach(function(node) {
      hash_to_node[node.hash] = node;
    });

    var links = [];
    nodes.forEach(function(node) {
      node.parents.forEach(function(parent) {
        links.push({source: node, target: hash_to_node[parent]});
      });
    });

    var tip_node, tip_length = data.tips.length;
    for(var i = 0; i < tip_length; i++) {
      tip_node = hash_to_node[data.tips[i]];
      tip_node.y = height - 10;
      tip_node.x = (width / (tip_length + 1)) * (i + 1);
      tip_node.fixed = true;
    };

    force.nodes(nodes)
      .links(links)
      .start();

    var link = svg.selectAll(".link")
      .data(links)
      .enter().append("line")
      .attr("class", "link");

    function hilight(id) {
      hash_to_node[id].parents.forEach(function(par) {
        hilight(par);
      });
      $(document.getElementById(id)).addClass("selected");
    }

    var last_node = null;
    var node = svg.selectAll(".node")
      .data(nodes)
      .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .call(force.drag)
      .on('click', function(node) {
        if (last_node !== null)
          d3.select(last_node).attr('r', 5);

        d3.select(this).attr('r', 10);
        last_node = this;

        $(".gref-taggable").removeClass("selected");
        hilight(node.hash);
      });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

    });

    return this;
  },

  install: function() {
    $("#gref-content")[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.install();
  }
});
var rendered_gref = new Gref();
var rendered_gref_content;
<commit_msg>Run the footer all the way down the sidebar<commit_after>function Groundstation() {
  this.channels = new Channels();
  this.channels.url = '/channels';

  this.active_grefs = new Grefs();

  this.username = localStorage.getItem("airship.committer") || "Anonymous Coward";

  this.renderers = {};
  this.validators = {};
}
function init_airship(groundstation) {
  _.each(groundstation.channels.models, function(channel) {
    new ChannelTab({
      model: channel,
      id: channel.attributes["name"]
    });
  });
  rendered_gref_content = new RenderedGref({
    model: rendered_gref
  });
  // Wire up user switching
  // TODO Currently not stored because I haven't decided where it should live. PRobably git-config(5)

  $("#current-user-name").html(groundstation.username);
  $("#current-user-name").on('click', function() {
    var username = prompt("Username for committing:");
    if (username !== null) {
      groundstation.username = username;
      $("#current-user-name").html(groundstation.username);
      try {
        localStorage.setItem("airship.committer", username);
      } catch (e) {
        console.log("Not setting committer name in localStorage");
      }
    }
  });
  var new_gref = {
    title: $("#new-gref-title").text(),
    body: $("#new-gref-body")[0].value,
    name: $("#new-gref-name").text()
  };
  var new_gref_validator = groundstation.validators.gref(new_gref.name, new_gref.title, new_gref.body);

  $("#new-gref").on('click', function() {
    $("#new-gref-title").text(new_gref.title);
    $("#new-gref-body")[0].value = new_gref.body;
    $("#new-gref-name").text(new_gref.name);
    var modal = $("#new-gref-modal");
    modal.modal();
  });
  $("#new-gref-cancel").on('click', function() {
    $("#new-gref-modal").modal('hide');
  });
  $("#new-gref-create").on('click', function() {
    var title = $("#new-gref-title").text(),
        body = $("#new-gref-body")[0].value,
        name = $("#new-gref-name").text(),
        protocol = $("#new-gref-protocol").text();

    if (new_gref_validator(name, title, body)) {
      $.ajax({
        type: "PUT",
        url: groundstation.active_grefs.url,
        data: {
          title: title,
          body: body,
          name: name,
          protocol: protocol,

          user: groundstation.username

        },
        success: function(data, st, xhr) {
          $("#new-gref-modal").modal('hide');
          groundstation.active_grefs.redraw();
        }
      });
    } else {
      // TODO Actually give the user something to go with
      alert("Validation failed!");
    }
  });
}

var Channel = Backbone.Model.extend();
var Channels = Backbone.Collection.extend({
  model: Channel
});

var Gref = Backbone.Model.extend();
var Grefs = Backbone.Collection.extend({
  model: Gref
});

var GrefMenuItem = Backbone.View.extend({
  tagName: "li",
  className: "gref",

  template: '{{identifier}}',

  getUrl: function() {
    return "/gref/" + this.model.attributes["channel"] + "/" + this.model.attributes["identifier"];
  },

  render: function() {
    this.$el.html(this.template.replace("{{identifier}}", this.model.attributes["identifier"]));
    return this;
  },

  select: function() {
    var active_el = this.el;
    $(this.el.parentElement.children).removeClass("active");
    rendered_gref.url = this.getUrl();
    rendered_gref.fetch({
      success: function(model, response, options) {
        $(active_el).addClass("active");
        rendered_gref_content.render();
      }
    });
  },

  events: {
    "click .select":  "select"
  },

  install: function() {
    $('#current-grefs')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }
});

var visible_grefs = [];
var ChannelTab = Backbone.View.extend({

  tagName: "li",

  className: "",

  template: '{{name}}',

  render: function() {
    this.$el.html(this.template.replace("{{name}}", this.model.attributes["name"]));
    return this;
  },

  select: function() {
    var self = this;
    var current_grefs = $("#current-grefs")[0];
    groundstation.active_grefs.url = '/grefs/' + this.model.attributes["name"];
    groundstation.active_grefs.redraw = function() {
      groundstation.active_grefs.fetch({
        success: function(collection, response, options) {
          $("#active-channel").html(self.model.attributes["name"]);
          $("#gref-container").show();
          _.each(visible_grefs, function(el) { el.remove(); });
          _.each(collection.models, function(gref) {
            visible_grefs.push(new GrefMenuItem({
              model: gref
            }));
          });
        }
      });
    };
    groundstation.active_grefs.redraw();
  },

  events: {
    "click .select":          "select"
  },

  install: function() {
    $('#channels-content')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }

});

function buildCommentBox(div, model) {
  var row, input, span, submit;

  row = document.createElement("div");
  row.className = "input-group";

  input = document.createElement("textarea");
  input.setAttribute('rows', 7);
  input.contentEditable = true;
  input.id = "new-comment-body";

  span = document.createElement("span");
  span.className = "input-group-btn";

  submit = document.createElement("button");
  submit.className = "btn";
  submit.id = "new-comment-submit";
  $(submit).text("Submit");
  span.appendChild(submit);

  row.appendChild(input);
  row.appendChild(span);

  $(submit).on('click', function(ev) {
    $.ajax({
        type: "POST",
        url: model.url,
        data: {
            body: input.value,
            parents: JSON.stringify(model.attributes["tips"]),
            user: groundstation.username

        },
        success: function(data, st, xhr) {
            rendered_gref.fetch();
            console.log("Successfully updated groundstation");
        }
    });
    console.log("Sending new comment to groundstation");
  });

  div.appendChild(row);
}

var RenderedGref = Backbone.View.extend({

  tagName: "div",
  className: "",

  render: function() {
    var self = this;
    var content = this.model.attributes["content"];
    var root = this.model.attributes["root"];
    var renderer = null;

    $(this.$el).children().remove();
    $("#gref-graph").children().remove();

    renderer = (function() {
      for (var renderer in groundstation.renderers) {
        if (groundstation.renderers.hasOwnProperty(renderer)) {
          if (root.protocol.search(renderer) === 0)
            return groundstation.renderers[renderer];
        }
      }
    })();
    if (renderer === null) {
      console.log("Unhandled protocol: " + root.protocol);
      return this;
    }

    // Stick the root object in the DOM to make parent linking sane.
    (function() {
      var el = document.createElement("div");
      el.setAttribute("id", root.hash);
      self.el.appendChild(el);
    })();

    _.each(content, function(item) {
      var el = renderer(item);
      if (el) {
        el.setAttribute("id", item.hash);
        var signature = self.model.attributes.signatures[item.hash];
        if (signature !== undefined) {
          if (signature === false) {
            el.setAttribute("data-invalid-signature", "true");
          } else {
            el.setAttribute("data-signature", signature);
          }
        }
        self.el.appendChild(el);
      }
    });
    buildCommentBox(self.el, self.model);

    var graph_span = $("#gref-graph-span");
    var width  = graph_span.width(),
                              // 40 pix header, 20 pix footer
        height = document.documentElement.clientHeight - 60;

    var force = d3.layout.force()
      .charge(-120)
      .size([width, height])
      .linkDistance(30);

    var svg = d3.select("#gref-graph").append("svg")
      .attr("width", width)
      .attr("height", height);;

    var data = this.model.attributes;
    var nodes = data.content;
    data.root.parents = [];
    data.root.fixed = true;
    data.root.x = width / 2;
    data.root.y = 10;
    nodes.push(data.root);

    var hash_to_node = {};
    nodes.forEach(function(node) {
      hash_to_node[node.hash] = node;
    });

    var links = [];
    nodes.forEach(function(node) {
      node.parents.forEach(function(parent) {
        links.push({source: node, target: hash_to_node[parent]});
      });
    });

    var tip_node, tip_length = data.tips.length;
    for(var i = 0; i < tip_length; i++) {
      tip_node = hash_to_node[data.tips[i]];
      tip_node.y = height - 10;
      tip_node.x = (width / (tip_length + 1)) * (i + 1);
      tip_node.fixed = true;
    };

    force.nodes(nodes)
      .links(links)
      .start();

    var link = svg.selectAll(".link")
      .data(links)
      .enter().append("line")
      .attr("class", "link");

    function hilight(id) {
      hash_to_node[id].parents.forEach(function(par) {
        hilight(par);
      });
      $(document.getElementById(id)).addClass("selected");
    }

    var last_node = null;
    var node = svg.selectAll(".node")
      .data(nodes)
      .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .call(force.drag)
      .on('click', function(node) {
        if (last_node !== null)
          d3.select(last_node).attr('r', 5);

        d3.select(this).attr('r', 10);
        last_node = this;

        $(".gref-taggable").removeClass("selected");
        hilight(node.hash);
      });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

    });

    return this;
  },

  install: function() {
    $("#gref-content")[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.install();
  }
});
var rendered_gref = new Gref();
var rendered_gref_content;
<|endoftext|>