<commit_before>/**
 * Register a component plugin as being loaded. returns true if compoent plugin already registered
 * @param {object} Vue
 * @param {string} Component name
 * @param {object} Component definition
 */
export function registerComponent (Vue, name, def) {
  Vue._bootstrap_vue_components_ = Vue._bootstrap_vue_components_ || {}
  const loaded = Vue._bootstrap_vue_components_[name]
  if (!loaded && def && name) {
    Vue._bootstrap_vue_components_[name] = true
    Vue.component(name, def)
  }
  return loaded
}

/**
 * Register a group of components as being loaded.
 * @param {object} Vue
 * @param {object} Object of component definitions
 */
export function registerComponents (Vue, components) {
  for (let component in components) {
    registerComponent(Vue, component, components[component])
  }
}

/**
 * Register a directive as being loaded. returns true if directive plugin already registered
 * @param {object} Vue
 * @param {string} Directive name
 * @param {object} Directive definition
 */
export function registerDirective (Vue, name, def) {
  Vue._bootstrap_vue_directives_ = Vue._bootstrap_vue_directives_ || {}
  const loaded = Vue._bootstrap_vue_directives_[name]
  if (!loaded && def && name) {
    Vue._bootstrap_vue_directives_[name] = true
    Vue.directive(name, def)
  }
  return loaded
}

/**
 * Register a group of directives as being loaded.
 * @param {object} Vue
 * @param {object} Object of directive definitions
 */
export function registerDirectives (Vue, directives) {
  for (let directive in directives) {
    registerDirective(Vue, directive, directives[directive])
  }
}

/**
 * Install plugin if window.Vue available
 * @param {object} Plugin definition
 */
export function vueUse (VuePlugin) {
  if (typeof window !== 'undefined' && window.Vue) {
    window.Vue.use(VuePlugin)
  }
}
<commit_msg>chore: fix comment typo in plugins.js (#2147)<commit_after>/**
 * Register a component plugin as being loaded. returns true if component plugin already registered
 * @param {object} Vue
 * @param {string} Component name
 * @param {object} Component definition
 */
export function registerComponent (Vue, name, def) {
  Vue._bootstrap_vue_components_ = Vue._bootstrap_vue_components_ || {}
  const loaded = Vue._bootstrap_vue_components_[name]
  if (!loaded && def && name) {
    Vue._bootstrap_vue_components_[name] = true
    Vue.component(name, def)
  }
  return loaded
}

/**
 * Register a group of components as being loaded.
 * @param {object} Vue
 * @param {object} Object of component definitions
 */
export function registerComponents (Vue, components) {
  for (let component in components) {
    registerComponent(Vue, component, components[component])
  }
}

/**
 * Register a directive as being loaded. returns true if directive plugin already registered
 * @param {object} Vue
 * @param {string} Directive name
 * @param {object} Directive definition
 */
export function registerDirective (Vue, name, def) {
  Vue._bootstrap_vue_directives_ = Vue._bootstrap_vue_directives_ || {}
  const loaded = Vue._bootstrap_vue_directives_[name]
  if (!loaded && def && name) {
    Vue._bootstrap_vue_directives_[name] = true
    Vue.directive(name, def)
  }
  return loaded
}

/**
 * Register a group of directives as being loaded.
 * @param {object} Vue
 * @param {object} Object of directive definitions
 */
export function registerDirectives (Vue, directives) {
  for (let directive in directives) {
    registerDirective(Vue, directive, directives[directive])
  }
}

/**
 * Install plugin if window.Vue available
 * @param {object} Plugin definition
 */
export function vueUse (VuePlugin) {
  if (typeof window !== 'undefined' && window.Vue) {
    window.Vue.use(VuePlugin)
  }
}
<|endoftext|>


<commit_before>/* jshint esversion: 6 */
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import EventListener from 'react-event-listener';
import keycode from 'keycode';
import {dateTimeFormat, formatIso, isEqualDate} from './dateUtils';
import DatePickerDialog from './DatePickerDialog';
import TextField from '../TextField';

class DatePicker extends Component {
  static propTypes = {
    /**
     * Constructor for date formatting for the specified `locale`.
     * The constructor must follow this specification: ECMAScript Internationalization API 1.0 (ECMA-402).
     * `Intl.DateTimeFormat` is supported by most modern browsers, see http://caniuse.com/#search=intl,
     * otherwise https://github.com/andyearnshaw/Intl.js is a good polyfill.
     *
     * By default, a built-in `DateTimeFormat` is used which supports the 'en-US' `locale`.
     */
    DateTimeFormat: PropTypes.func,
    /**
     * If true, automatically accept and close the picker on select a date.
     */
    autoOk: PropTypes.bool,
    /**
     * Override the default text of the 'Cancel' button.
     */
    cancelLabel: PropTypes.node,
    /**
     * The css class name of the root element.
     */
    className: PropTypes.string,
    /**
     * Used to control how the Date Picker will be displayed when the input field is focused.
     * `dialog` (default) displays the DatePicker as a dialog with a modal.
     * `inline` displays the DatePicker below the input field (similar to auto complete).
     */
    container: PropTypes.oneOf(['dialog', 'inline']),
    /**
     * This is the initial date value of the component.
     * If either `value` or `valueLink` is provided they will override this
     * prop with `value` taking precedence.
     */
    defaultDate: PropTypes.object,
    /**
     * Override the inline-styles of DatePickerDialog's Container element.
     */
    dialogContainerStyle: PropTypes.object,
    /**
     * Disable the ability to use the escape key to dismiss the date picker when opened in dialog mode.
     */
    disableDismissWithEscapeOnDialog: PropTypes.bool,
    /**
     * Disables the year selection in the date picker.
     */
    disableYearSelection: PropTypes.bool,
    /**
     * Disables the DatePicker.
     */
    disabled: PropTypes.bool,
    /**
     * Used to change the first day of week. It varies from
     * Saturday to Monday between different locales.
     * The allowed range is 0 (Sunday) to 6 (Saturday).
     * The default is `1`, Monday, as per ISO 8601.
     */
    firstDayOfWeek: PropTypes.number,
    /**
     * This function is called to format the date displayed in the input field, and should return a string.
     * By default if no `locale` and `DateTimeFormat` is provided date objects are formatted to ISO 8601 YYYY-MM-DD.
     *
     * @param {object} date Date object to be formatted.
     * @returns {any} The formatted date.
     */
    formatDate: PropTypes.func,
    /**
     * Hide date display
     */
    hideCalendarDate: PropTypes.bool,
    /**
     * The id value used for the component.
     * This will be used as a base for all child components also.
     * If not provided the class name along with appropriate properties and a random number will be used.
     */
    id: PropTypes.string,
    /**
     * Locale used for formatting the `DatePicker` date strings. Other than for 'en-US', you
     * must provide a `DateTimeFormat` that supports the chosen `locale`.
     */
    locale: PropTypes.string,
    /**
     * The ending of a range of valid dates. The range includes the endDate.
     * The default value is current date + 100 years.
     */
    maxDate: PropTypes.object,
    /**
     * The beginning of a range of valid dates. The range includes the startDate.
     * The default value is current date - 100 years.
     */
    minDate: PropTypes.object,
    /**
     * Tells the component to display the picker in portrait or landscape mode.
     */
    mode: PropTypes.oneOf(['portrait', 'landscape']),
    /**
     * Override the default text of the 'OK' button.
     */
    okLabel: PropTypes.node,
    /**
     * Callback function that is fired when the date value changes.
     *
     * @param {null} null Since there is no particular event associated with the change,
     * the first argument will always be null.
     * @param {object} date The new date.
     */
    onChange: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's dialog is dismissed.
     */
    onDismiss: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's `TextField` gains focus.
     */
    onFocus: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's dialog is shown.
     */
    onShow: PropTypes.func,
    /**
     * Callback function that is fired when a touch tap event occurs on the Date Picker's `TextField`.
     *
     * @param {object} event TouchTap event targeting the `TextField`.
     */
    onTouchTap: PropTypes.func,
    /**
     * If true sets the datepicker to open to year selection first.
     */
    openToYearSelection: PropTypes.bool,
    /**
     * Callback function used to determine if a day's entry should be disabled on the calendar.
     *
     * @param {object} day Date object of a day.
     * @returns {boolean} Indicates whether the day should be disabled.
     */
    shouldDisableDate: PropTypes.func,
    /**
     * Override the inline-styles of the root element.
     */
    style: PropTypes.object,
    /**
     * Override the inline-styles of DatePicker's TextField element.
     */
    textFieldStyle: PropTypes.object,
    /**
     * This object should contain methods needed to build the calendar system.
     *
     * Useful for building a custom calendar system. Refer to the
     * [source code](https://github.com/callemall/material-ui/blob/master/src/DatePicker/dateUtils.js)
     * and an [example implementation](https://github.com/alitaheri/material-ui-persian-date-picker-utils)
     * for more information.
     */
    utils: PropTypes.object,
    /**
     * Sets the date for the Date Picker programmatically.
     */
    value: PropTypes.object,
  };

  static defaultProps = {
    autoOk: false,
    container: 'dialog',
    disabled: false,
    disableDismissWithEscapeOnDialog: false,
    disableYearSelection: false,
    firstDayOfWeek: 1,
    hideCalendarDate: false,
    style: {},
    openToYearSelection: false,
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  state = {
    date: undefined,
  };

  componentWillMount() {
    const {
      id, // eslint-disable-line no-unused-vars
    } = this.props;

    this.setState({
      date: this.isControlled() ? this.getControlledDate() : this.props.defaultDate,
    });

    const uniqueId = `${this.constructor.name}-${Math.floor(Math.random() * 0xFFFF)}`;
    this.uniqueId = uniqueId.replace(/[^A-Za-z0-9-]/gi, '');
  }

  componentWillReceiveProps(nextProps) {
    if (this.isControlled()) {
      const newDate = this.getControlledDate(nextProps);
      if (!isEqualDate(this.state.date, newDate)) {
        this.setState({
          date: newDate,
        });
      }
    }
  }

  getDate() {
    return this.state.date;
  }

  /**
   * Open the date-picker dialog programmatically from a parent.
   */
  openDialog() {
    /**
     * if the date is not selected then set it to new date
     * (get the current system date while doing so)
     * else set it to the currently selected date
     */
    if (this.state.date !== undefined) {
      this.setState({
        dialogDate: this.getDate(),
      }, this.refs.dialogWindow.show);
    } else {
      this.setState({
        dialogDate: new Date(),
      }, this.refs.dialogWindow.show);
    }
  }

  /**
   * Alias for `openDialog()` for an api consistent with TextField.
   */
  focus() {
    this.openDialog();
  }

  handleAccept = (date) => {
    if (!this.isControlled()) {
      this.setState({
        date: date,
      });
    }
    if (this.props.onChange) {
      this.props.onChange(null, date);
    }
  };

  handleFocus = (event) => {
    if (this.props.onFocus) {
      this.props.onFocus(event);
    }
  };

  handleTouchTap = (event) => {
    if (this.props.onTouchTap) {
      this.props.onTouchTap(event);
    }

    if (!this.props.disabled) {
      setTimeout(() => {
        this.openDialog();
      }, 0);
    }
  };

  isControlled() {
    return this.props.hasOwnProperty('value');
  }

  getControlledDate(props = this.props) {
    if (props.value instanceof Date) {
      return props.value;
    }
  }

  formatDate = (date) => {
    if (this.props.locale) {
      const DateTimeFormat = this.props.DateTimeFormat || dateTimeFormat;
      return new DateTimeFormat(this.props.locale, {
        day: 'numeric',
        month: 'numeric',
        year: 'numeric',
      }).format(date);
    } else {
      return formatIso(date);
    }
  };

  /*
   * If the user presses a key and that key is enter, popup the picker dialog.
   * Only do this if the date picker is actually enabled though.
   */
  handleKeyEvent = (event) => {
    if (!this.props.disabled && (keycode(event) === 'enter' || keycode(event) === 'space')) {
      this.openDialog();
    }
  };

  render() {
    const {
      id,
      DateTimeFormat,
      autoOk,
      cancelLabel,
      className,
      container,
      defaultDate, // eslint-disable-line no-unused-vars
      dialogContainerStyle,
      disableDismissWithEscapeOnDialog,
      disableYearSelection,
      firstDayOfWeek,
      formatDate: formatDateProp,
      locale,
      maxDate,
      minDate,
      mode,
      okLabel,
      onDismiss,
      onFocus, // eslint-disable-line no-unused-vars
      onShow,
      onTouchTap, // eslint-disable-line no-unused-vars
      openToYearSelection,
      shouldDisableDate,
      hideCalendarDate,
      style,
      textFieldStyle,
      utils,
      ...other
    } = this.props;

    const {prepareStyles} = this.context.muiTheme;
    const formatDate = formatDateProp || this.formatDate;
    const inputId = id || this.uniqueId;
    const divId = `${inputId}-div`;
    const textFieldId = `${inputId}-textField`;
    const datePickerId = `${inputId}-datePicker`;

    return (
      <div id={divId} className={className} style={prepareStyles(Object.assign({}, style))} >
        <EventListener target={divId} onKeyDown={this.handleKeyEvent} />
        <DatePickerDialog
          id={datePickerId}
          DateTimeFormat={DateTimeFormat}
          autoOk={autoOk}
          cancelLabel={cancelLabel}
          container={container}
          containerStyle={dialogContainerStyle}
          disableEscapeKeyForDialogs={disableDismissWithEscapeOnDialog}
          disableYearSelection={disableYearSelection}
          firstDayOfWeek={firstDayOfWeek}
          initialDate={this.state.dialogDate}
          locale={locale}
          maxDate={maxDate}
          minDate={minDate}
          mode={mode}
          okLabel={okLabel}
          onAccept={this.handleAccept}
          onShow={onShow}
          onDismiss={onDismiss}
          ref="dialogWindow"
          shouldDisableDate={shouldDisableDate}
          hideCalendarDate={hideCalendarDate}
          openToYearSelection={openToYearSelection}
          utils={utils}
        />
        <TextField
          id={textFieldId}
          role="textbox"
          aria-label="Date Picker"
          {...other}
          onFocus={this.handleFocus}
          onTouchTap={this.handleTouchTap}
          ref="input"
          style={textFieldStyle}
          value={this.state.date ? formatDate(this.state.date) : ''}
        />
      </div>
    );
  }
}

export default DatePicker;
<commit_msg>DatePicker - fixed issue were a given ID was overridden (issue #215)<commit_after>/* jshint esversion: 6 */
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import EventListener from 'react-event-listener';
import keycode from 'keycode';
import {dateTimeFormat, formatIso, isEqualDate} from './dateUtils';
import DatePickerDialog from './DatePickerDialog';
import TextField from '../TextField';

class DatePicker extends Component {
  static propTypes = {
    /**
     * Constructor for date formatting for the specified `locale`.
     * The constructor must follow this specification: ECMAScript Internationalization API 1.0 (ECMA-402).
     * `Intl.DateTimeFormat` is supported by most modern browsers, see http://caniuse.com/#search=intl,
     * otherwise https://github.com/andyearnshaw/Intl.js is a good polyfill.
     *
     * By default, a built-in `DateTimeFormat` is used which supports the 'en-US' `locale`.
     */
    DateTimeFormat: PropTypes.func,
    /**
     * If true, automatically accept and close the picker on select a date.
     */
    autoOk: PropTypes.bool,
    /**
     * Override the default text of the 'Cancel' button.
     */
    cancelLabel: PropTypes.node,
    /**
     * The css class name of the root element.
     */
    className: PropTypes.string,
    /**
     * Used to control how the Date Picker will be displayed when the input field is focused.
     * `dialog` (default) displays the DatePicker as a dialog with a modal.
     * `inline` displays the DatePicker below the input field (similar to auto complete).
     */
    container: PropTypes.oneOf(['dialog', 'inline']),
    /**
     * This is the initial date value of the component.
     * If either `value` or `valueLink` is provided they will override this
     * prop with `value` taking precedence.
     */
    defaultDate: PropTypes.object,
    /**
     * Override the inline-styles of DatePickerDialog's Container element.
     */
    dialogContainerStyle: PropTypes.object,
    /**
     * Disable the ability to use the escape key to dismiss the date picker when opened in dialog mode.
     */
    disableDismissWithEscapeOnDialog: PropTypes.bool,
    /**
     * Disables the year selection in the date picker.
     */
    disableYearSelection: PropTypes.bool,
    /**
     * Disables the DatePicker.
     */
    disabled: PropTypes.bool,
    /**
     * Used to change the first day of week. It varies from
     * Saturday to Monday between different locales.
     * The allowed range is 0 (Sunday) to 6 (Saturday).
     * The default is `1`, Monday, as per ISO 8601.
     */
    firstDayOfWeek: PropTypes.number,
    /**
     * This function is called to format the date displayed in the input field, and should return a string.
     * By default if no `locale` and `DateTimeFormat` is provided date objects are formatted to ISO 8601 YYYY-MM-DD.
     *
     * @param {object} date Date object to be formatted.
     * @returns {any} The formatted date.
     */
    formatDate: PropTypes.func,
    /**
     * Hide date display
     */
    hideCalendarDate: PropTypes.bool,
    /**
     * The id value used for the component.
     * This will be used as a base for all child components also.
     * If not provided the class name along with appropriate properties and a random number will be used.
     */
    id: PropTypes.string,
    /**
     * Locale used for formatting the `DatePicker` date strings. Other than for 'en-US', you
     * must provide a `DateTimeFormat` that supports the chosen `locale`.
     */
    locale: PropTypes.string,
    /**
     * The ending of a range of valid dates. The range includes the endDate.
     * The default value is current date + 100 years.
     */
    maxDate: PropTypes.object,
    /**
     * The beginning of a range of valid dates. The range includes the startDate.
     * The default value is current date - 100 years.
     */
    minDate: PropTypes.object,
    /**
     * Tells the component to display the picker in portrait or landscape mode.
     */
    mode: PropTypes.oneOf(['portrait', 'landscape']),
    /**
     * Override the default text of the 'OK' button.
     */
    okLabel: PropTypes.node,
    /**
     * Callback function that is fired when the date value changes.
     *
     * @param {null} null Since there is no particular event associated with the change,
     * the first argument will always be null.
     * @param {object} date The new date.
     */
    onChange: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's dialog is dismissed.
     */
    onDismiss: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's `TextField` gains focus.
     */
    onFocus: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's dialog is shown.
     */
    onShow: PropTypes.func,
    /**
     * Callback function that is fired when a touch tap event occurs on the Date Picker's `TextField`.
     *
     * @param {object} event TouchTap event targeting the `TextField`.
     */
    onTouchTap: PropTypes.func,
    /**
     * If true sets the datepicker to open to year selection first.
     */
    openToYearSelection: PropTypes.bool,
    /**
     * Callback function used to determine if a day's entry should be disabled on the calendar.
     *
     * @param {object} day Date object of a day.
     * @returns {boolean} Indicates whether the day should be disabled.
     */
    shouldDisableDate: PropTypes.func,
    /**
     * Override the inline-styles of the root element.
     */
    style: PropTypes.object,
    /**
     * Override the inline-styles of DatePicker's TextField element.
     */
    textFieldStyle: PropTypes.object,
    /**
     * This object should contain methods needed to build the calendar system.
     *
     * Useful for building a custom calendar system. Refer to the
     * [source code](https://github.com/callemall/material-ui/blob/master/src/DatePicker/dateUtils.js)
     * and an [example implementation](https://github.com/alitaheri/material-ui-persian-date-picker-utils)
     * for more information.
     */
    utils: PropTypes.object,
    /**
     * Sets the date for the Date Picker programmatically.
     */
    value: PropTypes.object,
  };

  static defaultProps = {
    autoOk: false,
    container: 'dialog',
    disabled: false,
    disableDismissWithEscapeOnDialog: false,
    disableYearSelection: false,
    firstDayOfWeek: 1,
    hideCalendarDate: false,
    style: {},
    openToYearSelection: false,
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  state = {
    date: undefined,
  };

  componentWillMount() {
    const {
      id, // eslint-disable-line no-unused-vars
    } = this.props;

    this.setState({
      date: this.isControlled() ? this.getControlledDate() : this.props.defaultDate,
    });

    const uniqueId = `${this.constructor.name}-${Math.floor(Math.random() * 0xFFFF)}`;
    this.uniqueId = uniqueId.replace(/[^A-Za-z0-9-]/gi, '');
  }

  componentWillReceiveProps(nextProps) {
    if (this.isControlled()) {
      const newDate = this.getControlledDate(nextProps);
      if (!isEqualDate(this.state.date, newDate)) {
        this.setState({
          date: newDate,
        });
      }
    }
  }

  getDate() {
    return this.state.date;
  }

  /**
   * Open the date-picker dialog programmatically from a parent.
   */
  openDialog() {
    /**
     * if the date is not selected then set it to new date
     * (get the current system date while doing so)
     * else set it to the currently selected date
     */
    if (this.state.date !== undefined) {
      this.setState({
        dialogDate: this.getDate(),
      }, this.refs.dialogWindow.show);
    } else {
      this.setState({
        dialogDate: new Date(),
      }, this.refs.dialogWindow.show);
    }
  }

  /**
   * Alias for `openDialog()` for an api consistent with TextField.
   */
  focus() {
    this.openDialog();
  }

  handleAccept = (date) => {
    if (!this.isControlled()) {
      this.setState({
        date: date,
      });
    }
    if (this.props.onChange) {
      this.props.onChange(null, date);
    }
  };

  handleFocus = (event) => {
    if (this.props.onFocus) {
      this.props.onFocus(event);
    }
  };

  handleTouchTap = (event) => {
    if (this.props.onTouchTap) {
      this.props.onTouchTap(event);
    }

    if (!this.props.disabled) {
      setTimeout(() => {
        this.openDialog();
      }, 0);
    }
  };

  isControlled() {
    return this.props.hasOwnProperty('value');
  }

  getControlledDate(props = this.props) {
    if (props.value instanceof Date) {
      return props.value;
    }
  }

  formatDate = (date) => {
    if (this.props.locale) {
      const DateTimeFormat = this.props.DateTimeFormat || dateTimeFormat;
      return new DateTimeFormat(this.props.locale, {
        day: 'numeric',
        month: 'numeric',
        year: 'numeric',
      }).format(date);
    } else {
      return formatIso(date);
    }
  };

  /*
   * If the user presses a key and that key is enter, popup the picker dialog.
   * Only do this if the date picker is actually enabled though.
   */
  handleKeyEvent = (event) => {
    if (!this.props.disabled && (keycode(event) === 'enter' || keycode(event) === 'space')) {
      this.openDialog();
    }
  };

  render() {
    const {
      id,
      DateTimeFormat,
      autoOk,
      cancelLabel,
      className,
      container,
      defaultDate, // eslint-disable-line no-unused-vars
      dialogContainerStyle,
      disableDismissWithEscapeOnDialog,
      disableYearSelection,
      firstDayOfWeek,
      formatDate: formatDateProp,
      locale,
      maxDate,
      minDate,
      mode,
      okLabel,
      onDismiss,
      onFocus, // eslint-disable-line no-unused-vars
      onShow,
      onTouchTap, // eslint-disable-line no-unused-vars
      openToYearSelection,
      shouldDisableDate,
      hideCalendarDate,
      style,
      textFieldStyle,
      utils,
      ...other
    } = this.props;

    const {prepareStyles} = this.context.muiTheme;
    const formatDate = formatDateProp || this.formatDate;
    const inputId = id || this.uniqueId;
    const textFieldId = `${inputId}-textField`;
    const datePickerId = `${inputId}-datePicker`;

    return (
      <div id={inputId} className={className} style={prepareStyles(Object.assign({}, style))} >
        <EventListener target={inputId} onKeyDown={this.handleKeyEvent} />
        <DatePickerDialog
          id={datePickerId}
          DateTimeFormat={DateTimeFormat}
          autoOk={autoOk}
          cancelLabel={cancelLabel}
          container={container}
          containerStyle={dialogContainerStyle}
          disableEscapeKeyForDialogs={disableDismissWithEscapeOnDialog}
          disableYearSelection={disableYearSelection}
          firstDayOfWeek={firstDayOfWeek}
          initialDate={this.state.dialogDate}
          locale={locale}
          maxDate={maxDate}
          minDate={minDate}
          mode={mode}
          okLabel={okLabel}
          onAccept={this.handleAccept}
          onShow={onShow}
          onDismiss={onDismiss}
          ref="dialogWindow"
          shouldDisableDate={shouldDisableDate}
          hideCalendarDate={hideCalendarDate}
          openToYearSelection={openToYearSelection}
          utils={utils}
        />
        <TextField
          id={textFieldId}
          role="textbox"
          aria-label="Date Picker"
          {...other}
          onFocus={this.handleFocus}
          onTouchTap={this.handleTouchTap}
          ref="input"
          style={textFieldStyle}
          value={this.state.date ? formatDate(this.state.date) : ''}
        />
      </div>
    );
  }
}

export default DatePicker;
<|endoftext|>


<commit_before>import uuid_v4 from 'uuid/v4'
import cookie_parser_generator from 'cookie-parser'
import session_generator from 'express-session'
import session_store_generator from 'connect-mongo'
import mongoose from 'mongoose'

const session_secret = uuid_v4()
export const cookie_parser = cookie_parser_generator(session_secret)
const session_store = session_store_generator(session_generator)
export const session = session_generator({
  cookie: {
    secure: true,
  },
  name: 'sessionId',
  proxy: true,
  resave: true,
  saveUninitialized: true,
  secret: session_secret,
  store: new session_store({
    mongooseConnection: mongoose.connection,
  }),
})
<commit_msg>Revert "Issue #12: support secure cookies"<commit_after>import uuid_v4 from 'uuid/v4'
import cookie_parser_generator from 'cookie-parser'
import session_generator from 'express-session'
import session_store_generator from 'connect-mongo'
import mongoose from 'mongoose'

const session_secret = uuid_v4()
export const cookie_parser = cookie_parser_generator(session_secret)
const session_store = session_store_generator(session_generator)
export const session = session_generator({
  name: 'sessionId',
  proxy: true,
  resave: true,
  saveUninitialized: true,
  secret: session_secret,
  store: new session_store({
    mongooseConnection: mongoose.connection,
  }),
})
<|endoftext|>


<commit_before>'use strict';

var db = require('mano').db,
	user = db.User.prototype,
	inventory = require('./_inventory'),
	reqRadio;

exports['step-guide'] = { class: { 'step-active': true } };

exports.step = function () {
	insert(inventory);
	section({ class: 'user-guide' },
			h1("1. Individual registration guide for companies"
			),
			form({ class: 'guide-form' },
				div({ class: 'guide-box' }, h2("Questions"),
					hr(),
					ul({ class: 'form-elements' },
					['businessActivity',
						'isOwner',
						'inventory',
						'surfaceArea', 'members',
						'companyType',
						'isShoppingGallery'],
					function (name) {
						if (name === 'inventory') {
							li(div({ class: 'dbjs-input-component' },
								label(user.getDescriptor(name).label, ":"),
								div({ class: 'control' }, input({ dbjs: user.getObservable(name) }))));
							div({ class: 'inventory-button' },
								a({ onclick: inventory.show },
									span({ class: 'fa fa-calculator icon' }, "Calculator"),
									span({ class: 'label' }, "Calculate the amount")
									)
								);
						} else {
							li(div({ class: 'dbjs-input-component' },
								label(user.getDescriptor(name).label, ":"),
								div({ class: 'control' }, input({ dbjs: user.getObservable(name) }))));
						}
					})),
				div({ class: 'guide-box' }, h2("Registrations"),
					hr(),
					ul(li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isBRequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label)))
					),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. ")
				),
				div({ class: 'guide-box' }, h2("Requirements"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-requirements-list' },
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
						" Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum " +
							"dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet," +
							" consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet: ",
						ul(li(reqRadio = input({ dbjs: user._isType, type: 'radio',
							renderOption: function (labelTxt) {
								var data = {};
								data.dom = li(label({ class: 'input-aside' },
									span(data.input = input()),
									span(labelTxt)));
								return data;
							}  }), " "))),
						li(
						"Please choose x docs in the list: ",
						ul(
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li({ class: 'disabled' },
								label({ class: 'input-aside' }, input({ dbjs: user._isBRequested,
															type: 'checkbox',
															disabled: 'disabled',
															value: 'checked' }),
									" ",
									span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isARequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label)))
						)
					)
					)
				),
				div({ class: 'guide-box' }, h2("Costs"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-costs-list' },
						li(span("Registration fee"), " ",
							span("$50'000")
							),
						li(span("Stamp duty for registration"), " ",
							span("$10'000")),
						li(span("Filing fees for memorandum"), " ",
							span("$45'000")),
						li({ class: 'guide-total-costs' },
								span("Total Costs:"), " ",
								span("$105'000")
							)
						)
				),
				button({ class: 'save-step-one', type: 'submit' },
					"Save and continue"
				)
			)
		);
	reqRadio._dbjsInput.listItems[0].appendChild(
		div({ class: 'disabler-range' }, // add 'disabled' class to disable ul
			ul(
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
					span(user.getDescriptor('isBRequested').label))),
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested,
						type: 'checkbox', value: 'checked' }), " ",
					span(user.getDescriptor('isBRequested').label)))
			),
			div({ class: 'disabler' })
			)
	);
};
<commit_msg>Added for and id to lable and input in guide page. #152<commit_after>'use strict';

var db = require('mano').db,
	user = db.User.prototype,
	inventory = require('./_inventory'),
	reqRadio;

exports['step-guide'] = { class: { 'step-active': true } };

exports.step = function () {
	insert(inventory);
	section({ class: 'user-guide' },
			h1("1. Individual registration guide for companies"
			),
			form({ class: 'guide-form' },
				div({ class: 'guide-box' }, h2("Questions"),
					hr(),
					ul({ class: 'form-elements' },
					['businessActivity',
						'isOwner',
						'inventory',
						'surfaceArea', 'members',
						'companyType',
						'isShoppingGallery'],
					function (name) {
						if (name === 'inventory') {
							li(div({ class: 'dbjs-input-component' },
								label({ for: 'input-' + name }, user.getDescriptor(name).label, ":"),
								div({ class: 'control' },
									input({ control: { id: 'input-' + name }, dbjs: user.getObservable(name) }))));
							div({ class: 'inventory-button' },
								a({ onclick: inventory.show },
									span({ class: 'fa fa-calculator icon' }, "Calculator"),
									span({ class: 'label' }, "Calculate the amount")
									)
								);
						} else {
							li(div({ class: 'dbjs-input-component' },
								label(
									{ for: 'input-' + name },
									user.getDescriptor(name).label,
									":"
								),
								div({ class: 'control' },
									input({ control: { id: 'input-' + name }, dbjs: user.getObservable(name) }))));
						}
					})),
				div({ class: 'guide-box' }, h2("Registrations"),
					hr(),
					ul(li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isBRequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label)))
					),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. ")
				),
				div({ class: 'guide-box' }, h2("Requirements"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-requirements-list' },
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
						" Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum " +
							"dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet," +
							" consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet: ",
						ul(li(reqRadio = input({ dbjs: user._isType, type: 'radio',
							renderOption: function (labelTxt) {
								var data = {};
								data.dom = li(label({ class: 'input-aside' },
									span(data.input = input()),
									span(labelTxt)));
								return data;
							}  }), " "))),
						li(
						"Please choose x docs in the list: ",
						ul(
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li({ class: 'disabled' },
								label({ class: 'input-aside' }, input({ dbjs: user._isBRequested,
															type: 'checkbox',
															disabled: 'disabled',
															value: 'checked' }),
									" ",
									span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isARequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label)))
						)
					)
					)
				),
				div({ class: 'guide-box' }, h2("Costs"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-costs-list' },
						li(span("Registration fee"), " ",
							span("$50'000")
							),
						li(span("Stamp duty for registration"), " ",
							span("$10'000")),
						li(span("Filing fees for memorandum"), " ",
							span("$45'000")),
						li({ class: 'guide-total-costs' },
								span("Total Costs:"), " ",
								span("$105'000")
							)
						)
				),
				button({ class: 'save-step-one', type: 'submit' },
					"Save and continue"
				)
			)
		);
	reqRadio._dbjsInput.listItems[0].appendChild(
		div({ class: 'disabler-range' }, // add 'disabled' class to disable ul
			ul(
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
					span(user.getDescriptor('isBRequested').label))),
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested,
						type: 'checkbox', value: 'checked' }), " ",
					span(user.getDescriptor('isBRequested').label)))
			),
			div({ class: 'disabler' })
			)
	);
};
<|endoftext|>


<commit_before>var formfiller = new FormFiller();
formfiller.loadForm();

/**
 * FormFiller
 *
 * Main FormFiller class, which handles all requests
 * @returns {FormFiller}
 */
function FormFiller() {

    var _version = '0.1.7';
    var _context = this;
    this.jsCode = 'javascript:/* FormFiller v'+_version+' */var d=document, e=new Event(\'change\'),z;function i(a){return d.getElementById(a)}function n(a){return d.getElementsByName(a)}';

    this.loadForm = function () {
        _loadJQuery();
    };

    var _loadJQuery = function () {
        if (typeof jQuery === 'undefined') {
            new Loader().script('//code.jquery.com/jquery-1.11.1.min.js', function(context){context.doLoadForm();}, _context);
        } else {
            _context.doLoadForm();
        }
    };

    this.doLoadForm = function () {
        if(jQuery('div#formfiller').length === 0){
            var html = '

Form Filler v'+_version+'

<input id="formfiller-bookmarkletname" style="margin-bottom:18px" value="'+document.title+'"> <input type="button" value="Save" onclick="javascript:formfiller.save();return false;">

 Click and drag this link to the bookmarks bar: My bookmarklet
×

';
            jQuery('body').append(html);
        }
    };

    this.save = function() {
        jQuery('form input:not(:hidden,:radio,:checkbox,:submit,:file), form textarea, form select, form input[type="radio"]:checked, form input[type="checkbox"]:checked').each(function(){
            if(_hasName(this) || _hasId(this)){
                if(_hasName(this) && _hasId(this) && _isRadioOrCheckbox(this)){
                    formfiller.jsCode += 'z=i("'+_getId(this)+'");z.checked=true;';
                } else if(_hasId(this)){
                    formfiller.jsCode += 'z=i("'+_getId(this)+'");z.value="'+_getValue(this)+'";'
                } else {
                    formfiller.jsCode += 'z=n("'+_getName(this)+'")[0];z.value="'+_getValue(this)+'";';
                }
                formfiller.jsCode += 'z.dispatchEvent(e);';
            }
        });
        jQuery('#bookmarklet').attr('href', this.jsCode + 'void(0);').html(jQuery('#formfiller-bookmarkletname').val()).parent('p').show();
        jQuery('#formfiller-formwrapper').hide();
    };

    var _hasName = function(element){
        return (_getName(element) !== undefined);
    };

    var _getName = function(element){
        return jQuery(element).attr('name');
    };

    var _hasId = function(element){
        return (_getId(element) !== undefined);
    };

    var _getId = function(element){
        return jQuery(element).attr('id');
    };

    var _isRadioOrCheckbox = function(element){
        return ((_nameHasArray(element)) || (_isType(element, ['radio', 'checkbox'])))
    };

    var _nameHasArray = function(element){
        return (_getName(element).indexOf('[]') >= 0)
    };

    var _isType = function(element, types){
        return (jQuery.inArray(jQuery(element).attr('type'), types) >= 0);
    };

    var _getValue = function(element){
        return jQuery(element).val().replace(/"/g, '\\"');
    };

}

/**
 * Loader
 *
 * Class for loading external files
 * Supported tags:
 *   - script
 *   - link
 * @returns {Loader}
 */
function Loader() {

    var TYPE = {
        SCRIPT: 'script'
    };

    var _fileLoaded = false;
    var _callback = null;
    var _context = null;

    this.script = function (url, callback, context) {
        _callback = callback;
        _context = context;
        _appendNewElementToBody(
            TYPE.SCRIPT
            , {
                src: url
                , type: 'text/javascript'
            }
        );
        _cleanup();
    };

    var _appendNewElementToBody = function (type, attrs) {
        _getFirstElementByTagName('body').appendChild(_createElement(type, attrs));
    };

    var _getFirstElementByTagName = function (name) {
        return document.getElementsByTagName(name)[0];
    };

    var _createElement = function (type, attrs) {
        var element = document.createElement(type);

        for (var key in attrs) {
            element.setAttribute(key, attrs[key]);
        }

        element.onload = element.onreadystatechage = function () {
            if (!_fileLoaded && (!this.readyState || ['loaded', 'complete'].indexOf(this.readyState) !== -1)) {
                _fileLoaded = true;
                element.onload = element.onreadystatechange = null;
                _getFirstElementByTagName('body').removeChild(element);
                _callback(_context);
            }
        };

        return element;
    };

    var _cleanup = function () {
        _fileLoaded = false;
    };

}
<commit_msg>Fix 'Cannot read property replace of null' #7<commit_after>var formfiller = new FormFiller();
formfiller.loadForm();

/**
 * FormFiller
 *
 * Main FormFiller class, which handles all requests
 * @returns {FormFiller}
 */
function FormFiller() {

    var _version = '0.1.7';
    var _context = this;
    this.jsCode = 'javascript:/* FormFiller v'+_version+' */var d=document, e=new Event(\'change\'),z;function i(a){return d.getElementById(a)}function n(a){return d.getElementsByName(a)}';

    this.loadForm = function () {
        _loadJQuery();
    };

    var _loadJQuery = function () {
        if (typeof jQuery === 'undefined') {
            new Loader().script('//code.jquery.com/jquery-1.11.1.min.js', function(context){context.doLoadForm();}, _context);
        } else {
            _context.doLoadForm();
        }
    };

    this.doLoadForm = function () {
        if(jQuery('div#formfiller').length === 0){
            var html = '

Form Filler v'+_version+'

<input id="formfiller-bookmarkletname" style="margin-bottom:18px" value="'+document.title+'"> <input type="button" value="Save" onclick="javascript:formfiller.save();return false;">

 Click and drag this link to the bookmarks bar: My bookmarklet
×

';
            jQuery('body').append(html);
        }
    };

    this.save = function() {
        jQuery('form input:not(:hidden,:radio,:checkbox,:submit,:file), form textarea, form select, form input[type="radio"]:checked, form input[type="checkbox"]:checked').each(function(){
            if(_hasName(this) || _hasId(this)){
                if(_hasName(this) && _hasId(this) && _isRadioOrCheckbox(this)){
                    formfiller.jsCode += 'z=i("'+_getId(this)+'");z.checked=true;';
                } else if(_hasId(this)){
                    formfiller.jsCode += 'z=i("'+_getId(this)+'");z.value="'+_getValue(this)+'";'
                } else {
                    formfiller.jsCode += 'z=n("'+_getName(this)+'")[0];z.value="'+_getValue(this)+'";';
                }
                formfiller.jsCode += 'z.dispatchEvent(e);';
            }
        });
        jQuery('#bookmarklet').attr('href', this.jsCode + 'void(0);').html(jQuery('#formfiller-bookmarkletname').val()).parent('p').show();
        jQuery('#formfiller-formwrapper').hide();
    };

    var _hasName = function(element){
        return (_getName(element) !== undefined);
    };

    var _getName = function(element){
        return jQuery(element).attr('name');
    };

    var _hasId = function(element){
        return (_getId(element) !== undefined);
    };

    var _getId = function(element){
        return jQuery(element).attr('id');
    };

    var _isRadioOrCheckbox = function(element){
        return ((_nameHasArray(element)) || (_isType(element, ['radio', 'checkbox'])))
    };

    var _nameHasArray = function(element){
        return (_getName(element).indexOf('[]') >= 0)
    };

    var _isType = function(element, types){
        return (jQuery.inArray(jQuery(element).attr('type'), types) >= 0);
    };

    var _getValue = function(element){
        var value = jQuery(element).val();
        return (value === null) ? '' : value.replace(/"/g, '\\"');
    };

}

/**
 * Loader
 *
 * Class for loading external files
 * Supported tags:
 *   - script
 *   - link
 * @returns {Loader}
 */
function Loader() {

    var TYPE = {
        SCRIPT: 'script'
    };

    var _fileLoaded = false;
    var _callback = null;
    var _context = null;

    this.script = function (url, callback, context) {
        _callback = callback;
        _context = context;
        _appendNewElementToBody(
            TYPE.SCRIPT
            , {
                src: url
                , type: 'text/javascript'
            }
        );
        _cleanup();
    };

    var _appendNewElementToBody = function (type, attrs) {
        _getFirstElementByTagName('body').appendChild(_createElement(type, attrs));
    };

    var _getFirstElementByTagName = function (name) {
        return document.getElementsByTagName(name)[0];
    };

    var _createElement = function (type, attrs) {
        var element = document.createElement(type);

        for (var key in attrs) {
            element.setAttribute(key, attrs[key]);
        }

        element.onload = element.onreadystatechage = function () {
            if (!_fileLoaded && (!this.readyState || ['loaded', 'complete'].indexOf(this.readyState) !== -1)) {
                _fileLoaded = true;
                element.onload = element.onreadystatechange = null;
                _getFirstElementByTagName('body').removeChild(element);
                _callback(_context);
            }
        };

        return element;
    };

    var _cleanup = function () {
        _fileLoaded = false;
    };

}
<|endoftext|>


<commit_before>import globalStore from '../util/globalstore.jsx';
import keys from '../util/keys.jsx';
import assign from 'object-assign';
import 'whatwg-fetch-timeout';

const prepare=(url,options,defaults)=>{
    if (url === undefined) {
        return [undefined,undefined];
    }
    let ioptions=assign({},defaults,options);
    if ( !(ioptions && ioptions.useNavUrl !== undefined && !ioptions.useNavUrl)){
        url=globalStore.getData(keys.properties.navUrl)+url;
    }
    if (ioptions.timeout === undefined) ioptions.timeout=parseInt(globalStore.getData(keys.properties.networkTimeout));
    let headers=undefined;
    if ( !(ioptions && ioptions.noCache !== undefined && !ioptions.noCache)){
        headers={};
        headers['pragma']='no-cache';
        headers['cache-control']='no-cache';
    }
    let requestOptions={};
    if (headers) requestOptions.headers=headers;
    requestOptions.timeout=ioptions.timeout;
    return [url,requestOptions];
};

const handleJson=(rurl,requestOptions,options)=>{
    return new Promise((resolve,reject)=>{
        if (!rurl) {
            reject("missing url");
            return;
        }
        let sequence=undefined;
        if (options && options.sequenceFunction) sequence=options.sequenceFunction();
        fetch(rurl,requestOptions).then(
            (response)=>{
                if (response.status < 200 || response.status >= 300){
                    reject(response.statusText);
                    return;
                }
                if (response.ok){
                    return response.json();
                }
                else{
                    reject(response.statusText);
                }
            },
            (error)=>{
                reject(error.message);
            }).then((json)=>{
                if (sequence !== undefined){
                    if (sequence != options.sequenceFunction()) {
                        reject("sequence changed");
                        return;
                    }
                }
                if (! json){
                    reject("empty response");
                    return;
                }
                if ( ! (options && options.checkOk !== undefined && ! options.checkOk)){
                    if (! json.status || (json.status !== 'OK' && json.status != 'ok')){
                        reject("status: "+json.status);
                        return;
                    }
                }
                resolve(json);
            },(jsonError)=>{
                reject(jsonError);
            });
    });
};

const addParameters=(url,parameters)=>{
    if (!parameters) return url;
    for (let k in parameters){
        let v=parameters[k];
        if (v === undefined) continue;
        if (typeof(v) == 'function' || typeof(k) == 'object') continue;
        if (url.match(/\?/)) url+="&";
        else url+="?";
        url+=encodeURIComponent(k)+"="+encodeURIComponent(v);
    }
    return url;
};
let RequestHandler={
    /**
     * do a json get request
     * @param url
     * @param options:
     *        useNavUrl - (default: true) - prepend the navUrl to the provided url
     *        checkOk   - (default: true) - check if the response has a status field and this is set to "OK"
     *        noCache   - (default: true) - prevent caching
     *        timeout   - (default: statusQueryTimeout) - timeout
     *        sequenceFunction - if set: a function to return a sequence - if the one returned from start
     *                           does not match the on at the result we reject
     *        opt_parameter - object with request parameters
     */
    getJson:(url,options,opt_parameter)=>{
        let [rurl,requestOptions]=prepare(url,options);
        return handleJson(addParameters(rurl,opt_parameter),requestOptions,options);
    },

    postJson:(url,body,options,opt_parameters)=>{
        let [rurl,requestOptions]=prepare(url,options);
        requestOptions.method='POST';
        rurl=addParameters(rurl,opt_parameters);
        if (!requestOptions.headers) requestOptions.headers={};
        requestOptions.headers['content-type']='application/json';
        let encodedBody=JSON.stringify(body);
        if (avnav.android){
            return new Promise((resolve,reject)=> {
                let status=avnav.android.handleUpload(rurl, encodedBody);
                if (status == 'OK'){
                    resolve({status:status});
                    return;
                }
                else{
                    reject(status);
                    return;
                }
            });
        }
        requestOptions.body=encodedBody;
        return handleJson(rurl,requestOptions,options);
    },

    postPlain:(url,body,options,opt_parameters)=>{
        let [rurl,requestOptions]=prepare(url,options);
        rurl=addParameters(rurl,opt_parameters);
        requestOptions.method='POST';
        if (!requestOptions.headers) requestOptions.headers={};
        requestOptions.headers['content-type']='application/octet-string';
        if (avnav.android){
            return new Promise((resolve,reject)=> {
                let status=avnav.android.handleUpload(rurl, body);
                if (status == 'OK'){
                    resolve({status:status});
                    return;
                }
                else{
                    reject(status);
                    return;
                }
            });
        }
        requestOptions.body=body;
        return handleJson(rurl,requestOptions,options);
    },
    /**
     * do a json get request
     * @param url
     * @param options:
     *        useNavUrl - (default: false) - prepend the navUrl to the provided url
     *        noCache   - (default: false) - prevent caching
     */
    getHtmlOrText:(url,options,opt_parameter)=>{
        let [rurl,requestOptions]=prepare(url,options,{useNavUrl:false,noCache:false});
        return new Promise((resolve,reject)=>{
          rurl=addParameters(rurl,opt_parameter)
          if (!rurl) {
            reject("missing url");
            return;
          }
          let sequence=undefined;
          if (options && options.sequenceFunction) sequence=options.sequenceFunction();
          let finalResponse;
          fetch(rurl,requestOptions).then(
              (response)=>{
                  if (response.status < 200 || response.status >= 300){
                      reject(response.statusText);
                  }
                  if (response.ok){
                      finalResponse=response;
                      return response.text();
                  }
                  else{
                      reject(response.statusText);
                  }
              },
              (error)=>{
                  reject(error.message);
              }).then((text)=>{
                  if (sequence !== undefined){
                      if (sequence != options.sequenceFunction()) {
                          reject("sequence changed");
                          return;
                      }
                  }
                 resolve(text,finalResponse);
              },(error)=>{
                  reject(error);
              });
        });
    },

    /**
     * @param url {string}
     * @param file {File}
     * @param param parameter object
     *        all handlers get the param object as first parameter
     *        starthandler: will get the xhdr as second parameter - so it can be used for interrupts
     *        progresshandler: progressfunction
     *        okhandler: called when done
     *        errorhandler: called on error
     *        see https://mobiarch.wordpress.com/2012/08/21/html5-file-upload-with-progress-bar-using-jquery/
     */
    uploadFile: (url, file, param)=> {
        let type = "application/octet-stream";
        try {
            let xhr=new XMLHttpRequest();
            xhr.open('POST',url,true);
            xhr.setRequestHeader('Content-Type', type);
            xhr.addEventListener('load',(event)=>{
                if (xhr.status != 200){
                    if (param.errorhandler) param.errorhandler(param,xhr.statusText);
                    return;
                }
                let json=undefined;
                try {
                    json = JSON.parse(xhr.responseText);
                    if (! json.status || json.status != 'OK'){
                        if (param.errorhandler) param.errorhandler(param,"invalid status: "+json.status);
                        return;
                    }
                }catch (e){
                    if (param.errorhandler) param.errorhandler(param,e);
                    return;
                }
                if (param.okhandler) param.okhandler(param,json);
            });
            xhr.upload.addEventListener('progress',(event)=>{
                if (param.progresshandler) param.progresshandler(param,event);
            });
            xhr.addEventListener('error',(event)=>{
               if (param.errorhandler) param.errorhandler(param,"upload error");
            });
            if (param.starthandler) param.starthandler(param,xhr);
            xhr.send(file);
        } catch (e) {
            if (param.errorhandler) param.errorhandler(param,e);
        }
    }
};
Object.freeze(RequestHandler);

export default RequestHandler;<commit_msg>allow new style requests with options instead of url<commit_after>import globalStore from '../util/globalstore.jsx';
import keys from '../util/keys.jsx';
import assign from 'object-assign';
import 'whatwg-fetch-timeout';

const prepare=(url,options,defaults)=>{
    if (url === undefined) {
        return [undefined,undefined];
    }
    let rurl="";
    if (typeof(url) === 'string') rurl=url;
    let ioptions=assign({},defaults,options);
    if ( ioptions.useNavUrl !== false){
        rurl=globalStore.getData(keys.properties.navUrl)+rurl;
    }
    //new syntax for parametr object instead of url
    if (typeof(url) === 'object'){
        rurl=addParameters(rurl,url);
    }
    if (ioptions.timeout === undefined) ioptions.timeout=parseInt(globalStore.getData(keys.properties.networkTimeout));
    let headers=undefined;
    if ( !(ioptions && ioptions.noCache !== undefined && !ioptions.noCache)){
        headers={};
        headers['pragma']='no-cache';
        headers['cache-control']='no-cache';
    }
    let requestOptions={};
    if (headers) requestOptions.headers=headers;
    requestOptions.timeout=ioptions.timeout;
    return [rurl,requestOptions];
};

const handleJson=(rurl,requestOptions,options)=>{
    return new Promise((resolve,reject)=>{
        if (!rurl) {
            reject("missing url");
            return;
        }
        let sequence=undefined;
        if (options && options.sequenceFunction) sequence=options.sequenceFunction();
        fetch(rurl,requestOptions).then(
            (response)=>{
                if (response.status < 200 || response.status >= 300){
                    reject(response.statusText);
                    return;
                }
                if (response.ok){
                    return response.json();
                }
                else{
                    reject(response.statusText);
                }
            },
            (error)=>{
                reject(error.message);
            }).then((json)=>{
                if (sequence !== undefined){
                    if (sequence != options.sequenceFunction()) {
                        reject("sequence changed");
                        return;
                    }
                }
                if (! json){
                    reject("empty response");
                    return;
                }
                if ( ! (options && options.checkOk !== undefined && ! options.checkOk)){
                    if (! json.status || (json.status !== 'OK' && json.status != 'ok')){
                        reject("status: "+json.status);
                        return;
                    }
                }
                resolve(json);
            },(jsonError)=>{
                reject(jsonError);
            });
    });
};

const addParameters=(url,parameters)=>{
    if (!parameters) return url;
    for (let k in parameters){
        let v=parameters[k];
        if (v === undefined) continue;
        if (typeof(v) == 'function' || typeof(k) == 'object') continue;
        if (url.match(/\?/)) url+="&";
        else url+="?";
        url+=encodeURIComponent(k)+"="+encodeURIComponent(v);
    }
    return url;
};
let RequestHandler={
    /**
     * do a json get request
     * @param url - either string or object with request parameters
     * @param options:
     *        useNavUrl - (default: true) - prepend the navUrl to the provided url
     *        checkOk   - (default: true) - check if the response has a status field and this is set to "OK"
     *        noCache   - (default: true) - prevent caching
     *        timeout   - (default: statusQueryTimeout) - timeout
     *        sequenceFunction - if set: a function to return a sequence - if the one returned from start
     *                           does not match the on at the result we reject
     *        opt_parameter - object with request parameters
     * @param opt_parameter
     */
    getJson:(url,options,opt_parameter)=>{
        let [rurl,requestOptions]=prepare(url,options);
        return handleJson(addParameters(rurl,opt_parameter),requestOptions,options);
    },

    postJson:(url,body,options,opt_parameters)=>{
        let [rurl,requestOptions]=prepare(url,options);
        requestOptions.method='POST';
        rurl=addParameters(rurl,opt_parameters);
        if (!requestOptions.headers) requestOptions.headers={};
        requestOptions.headers['content-type']='application/json';
        let encodedBody=JSON.stringify(body);
        if (avnav.android){
            return new Promise((resolve,reject)=> {
                let status=avnav.android.handleUpload(rurl, encodedBody);
                if (status == 'OK'){
                    resolve({status:status});
                    return;
                }
                else{
                    reject(status);
                    return;
                }
            });
        }
        requestOptions.body=encodedBody;
        return handleJson(rurl,requestOptions,options);
    },

    postPlain:(url,body,options,opt_parameters)=>{
        let [rurl,requestOptions]=prepare(url,options);
        rurl=addParameters(rurl,opt_parameters);
        requestOptions.method='POST';
        if (!requestOptions.headers) requestOptions.headers={};
        requestOptions.headers['content-type']='application/octet-string';
        if (avnav.android){
            return new Promise((resolve,reject)=> {
                let status=avnav.android.handleUpload(rurl, body);
                if (status == 'OK'){
                    resolve({status:status});
                    return;
                }
                else{
                    reject(status);
                    return;
                }
            });
        }
        requestOptions.body=body;
        return handleJson(rurl,requestOptions,options);
    },
    /**
     * do a json get request
     * @param url either string or object with request parameters
     * @param options:
     *        useNavUrl - (default: false) - prepend the navUrl to the provided url
     *        noCache   - (default: false) - prevent caching
     * @param opt_parameter request parameters
     */
    getHtmlOrText:(url,options,opt_parameter)=>{
        let [rurl,requestOptions]=prepare(url,options,{useNavUrl:false,noCache:false});
        return new Promise((resolve,reject)=>{
          rurl=addParameters(rurl,opt_parameter)
          if (!rurl) {
            reject("missing url");
            return;
          }
          let sequence=undefined;
          if (options && options.sequenceFunction) sequence=options.sequenceFunction();
          let finalResponse;
          fetch(rurl,requestOptions).then(
              (response)=>{
                  if (response.status < 200 || response.status >= 300){
                      reject(response.statusText);
                  }
                  if (response.ok){
                      finalResponse=response;
                      return response.text();
                  }
                  else{
                      reject(response.statusText);
                  }
              },
              (error)=>{
                  reject(error.message);
              }).then((text)=>{
                  if (sequence !== undefined){
                      if (sequence != options.sequenceFunction()) {
                          reject("sequence changed");
                          return;
                      }
                  }
                 resolve(text,finalResponse);
              },(error)=>{
                  reject(error);
              });
        });
    },

    /**
     * @param url {string}
     * @param file {File}
     * @param param parameter object
     *        all handlers get the param object as first parameter
     *        starthandler: will get the xhdr as second parameter - so it can be used for interrupts
     *        progresshandler: progressfunction
     *        okhandler: called when done
     *        errorhandler: called on error
     *        see https://mobiarch.wordpress.com/2012/08/21/html5-file-upload-with-progress-bar-using-jquery/
     */
    uploadFile: (url, file, param)=> {
        let type = "application/octet-stream";
        try {
            let xhr=new XMLHttpRequest();
            xhr.open('POST',url,true);
            xhr.setRequestHeader('Content-Type', type);
            xhr.addEventListener('load',(event)=>{
                if (xhr.status != 200){
                    if (param.errorhandler) param.errorhandler(param,xhr.statusText);
                    return;
                }
                let json=undefined;
                try {
                    json = JSON.parse(xhr.responseText);
                    if (! json.status || json.status != 'OK'){
                        if (param.errorhandler) param.errorhandler(param,"invalid status: "+json.status);
                        return;
                    }
                }catch (e){
                    if (param.errorhandler) param.errorhandler(param,e);
                    return;
                }
                if (param.okhandler) param.okhandler(param,json);
            });
            xhr.upload.addEventListener('progress',(event)=>{
                if (param.progresshandler) param.progresshandler(param,event);
            });
            xhr.addEventListener('error',(event)=>{
               if (param.errorhandler) param.errorhandler(param,"upload error");
            });
            if (param.starthandler) param.starthandler(param,xhr);
            xhr.send(file);
        } catch (e) {
            if (param.errorhandler) param.errorhandler(param,e);
        }
    }
};
Object.freeze(RequestHandler);

export default RequestHandler;<|endoftext|>


<commit_before>'use strict';

angular.module('$strap.directives')

.directive('bsTimepicker', function($timeout, $strapConfig) {

  var TIME_REGEXP = '((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)';

  return {
    restrict: 'A',
    require: '?ngModel',
    link: function postLink(scope, element, attrs, controller) {

      // If we have a controller (i.e. ngModelController) then wire it up
      if(controller) {
        element.on('changeTime.timepicker', function(ev) {
          $timeout(function() {
            controller.$setViewValue(element.val());
          });
        });

        // Handle input time validity
        var timeRegExp = new RegExp('^' + TIME_REGEXP + '$', ['i']);

        // viewValue -> $parsers -> modelValue
        controller.$parsers.unshift(function(viewValue) {
          if (!viewValue || timeRegExp.test(viewValue)) {
            controller.$setValidity('time', true);
            return viewValue;
          } else {
            controller.$setValidity('time', false);
            return;
          }
        });

      }

      // Create datepicker
      element.attr('data-toggle', 'timepicker');
      element.parent().addClass('bootstrap-timepicker');
      element.timepicker($strapConfig.timepicker || {});
      var timepicker = element.data('timepicker');

      // Support add-on
      var component = element.siblings('[data-toggle="timepicker"]');
      if(component.length) {
        component.on('click', $.proxy(timepicker.showWidget, timepicker));
      }

    }
  };

});
<commit_msg>fix comment typo<commit_after>'use strict';

angular.module('$strap.directives')

.directive('bsTimepicker', function($timeout, $strapConfig) {

  var TIME_REGEXP = '((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)';

  return {
    restrict: 'A',
    require: '?ngModel',
    link: function postLink(scope, element, attrs, controller) {

      // If we have a controller (i.e. ngModelController) then wire it up
      if(controller) {
        element.on('changeTime.timepicker', function(ev) {
          $timeout(function() {
            controller.$setViewValue(element.val());
          });
        });

        // Handle input time validity
        var timeRegExp = new RegExp('^' + TIME_REGEXP + '$', ['i']);

        // viewValue -> $parsers -> modelValue
        controller.$parsers.unshift(function(viewValue) {
          if (!viewValue || timeRegExp.test(viewValue)) {
            controller.$setValidity('time', true);
            return viewValue;
          } else {
            controller.$setValidity('time', false);
            return;
          }
        });

      }

      // Create timepicker
      element.attr('data-toggle', 'timepicker');
      element.parent().addClass('bootstrap-timepicker');
      element.timepicker($strapConfig.timepicker || {});
      var timepicker = element.data('timepicker');

      // Support add-on
      var component = element.siblings('[data-toggle="timepicker"]');
      if(component.length) {
        component.on('click', $.proxy(timepicker.showWidget, timepicker));
      }

    }
  };

});
<|endoftext|>


<commit_before>"use strict";

var delimiters = {
    QUOTE: '"',
    AUTHOR: " By ",
}

class Parser {
    constructor() {
        this.getQuote = function(command){
            if (command.replace(/[^/"]/g, "").length !== 2)
                return null;

            let quote = command.split(delimiters.QUOTE);
            if (quote[0].length !== 3)
                return null;

            quote.shift();

            if (quote[0].length === 0)
                return null;

            return quote[0];
        };

        this.getAuther = function(command){
            command = command.replace(delimiters.AUTHOR, delimiters.AUTHOR.toLowerCase());

            if (command.indexOf(delimiters.AUTHOR.toLowerCase()) === -1)
                return null;

            let author = command.replace(delimiters.AUTHOR.toLowerCase(), "");
            if (author.length == 0)
                return null;

            return author.trim();
        };
    }

    parseCommand(command) {
        let quote, author;

        if (!(quote = this.getQuote(command)))
            return null;

        if (!(author = this.getAuther(command.replace('"' + quote + '"', ""))))
            return null;

        return {
            quote: quote,
            author: author,
        }
    }
}

module.exports = Parser;
<commit_msg>adding more logging<commit_after>"use strict";

var delimiters = {
    QUOTE: '"',
    AUTHOR: " By ",
}

class Parser {
    constructor() {
        this.getQuote = function(command){
            if (command.replace(/[^/"]/g, "").length !== 2)
                return null;

            let quote = command.split(delimiters.QUOTE);
            if (quote[0].length !== 3)
                return null;

            quote.shift();

            if (quote[0].length === 0)
                return null;

            console.log(quote[0]);
            return quote[0];
        };

        this.getAuther = function(command){
            command = command.replace(delimiters.AUTHOR, delimiters.AUTHOR.toLowerCase());

            if (command.indexOf(delimiters.AUTHOR.toLowerCase()) === -1)
                return null;

            let author = command.replace(delimiters.AUTHOR.toLowerCase(), "");
            if (author.length == 0)
                return null;

            return author.trim();
        };
    }

    parseCommand(command) {
        let quote, author;

        if (!(quote = this.getQuote(command)))
            return null;

        if (!(author = this.getAuther(command.replace('"' + quote + '"', ""))))
            return null;

        return {
            quote: quote,
            author: author,
        }
    }
}

module.exports = Parser;
<|endoftext|>