<commit_before>import React, { Component, PropTypes } from 'react';
import Draggable from '@bokuweb/react-draggable-custom';
import Resizable from 'react-resizable-box';

const boxStyle = {
  width: 'auto',
  height: 'auto',
  cursor: 'move',
  position: 'absolute',
};

export default class ResizableAndMovable extends Component {
  static propTypes = {
    // initAsResizing: PropTypes.object,
    onResizeStart: PropTypes.func,
    onResize: PropTypes.func,
    onResizeStop: PropTypes.func,
    onDragStart: PropTypes.func,
    onDrag: PropTypes.func,
    onDragStop: PropTypes.func,
    className: PropTypes.string,
    style: PropTypes.object,
    children: PropTypes.any,
    onTouchStart: PropTypes.func,
    onClick: PropTypes.func,
    onDoubleClick: PropTypes.func,
    dragHandlerClassName: PropTypes.string,
    resizerHandleStyle: PropTypes.shape({
      top: PropTypes.object,
      right: PropTypes.object,
      bottom: PropTypes.object,
      left: PropTypes.object,
      topRight: PropTypes.object,
      bottomRight: PropTypes.object,
      bottomLeft: PropTypes.object,
      topLeft: PropTypes.object,
    }),
    isResizable: PropTypes.shape({
      top: PropTypes.bool,
      right: PropTypes.bool,
      bottom: PropTypes.bool,
      left: PropTypes.bool,
      topRight: PropTypes.bool,
      bottomRight: PropTypes.bool,
      bottomLeft: PropTypes.bool,
      topLeft: PropTypes.bool,
    }),
    // canUpdateSizeByParent: PropTypes.bool,
    // canUpdatePositionByParent: PropTypes.bool,
    width: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
    ]),
    height: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
    ]),
    minWidth: PropTypes.number,
    minHeight: PropTypes.number,
    maxWidth: PropTypes.number,
    maxHeight: PropTypes.number,
    moveAxis: PropTypes.oneOf(['x', 'y', 'both', 'none']),
    moveGrid: PropTypes.arrayOf(PropTypes.number),
    resizeGrid: PropTypes.arrayOf(PropTypes.number),
    bounds: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object,
    ]),
    x: PropTypes.number,
    y: PropTypes.number,
    zIndex: PropTypes.number,
    lockAspectRatio: PropTypes.bool,
  };

  static defaultProps = {
    x: 0,
    y: 0,
    width: 100,
    height: 100,
    zIndex: 100,
    className: '',
    dragHandlerClassName: '',
    // initAsResizing: { enable: false, direction: 'bottomRight' },
    isResizable: {
      top: true,
      right: true,
      bottom: true,
      left: true,
      topRight: true,
      bottomRight: true,
      bottomLeft: true,
      topLeft: true,
    },
    // canUpdatePositionByParent: false,
    // canUpdateSizeByParent: false,
    style: {},
    moveAxis: 'both',
    moveGrid: [1, 1],
    onClick: () => {},
    onTouchStart: () => {},
    onDragStart: () => {},
    onDrag: () => {},
    onDragStop: () => {},
    onResizeStart: () => {},
    onResize: () => {},
    onResizeStop: () => {},
    resizeGrid: [1, 1],
    lockAspectRatio: false,
  }

  constructor(props) {
    super(props);
    this.state = {
      isDraggable: true,
      isMounted: false,
      x: props.x,
      y: props.y,
      original: { x: props.x, y: props.y },
    };
    this.isResizing = false;
    this.onDragStart = this.onDragStart.bind(this);
    this.onDrag = this.onDrag.bind(this);
    this.onDragStop = this.onDragStop.bind(this);
    this.onResizeStart = this.onResizeStart.bind(this);
    this.onResize = this.onResize.bind(this);
    this.onResizeStop = this.onResizeStop.bind(this);
  }

  componentDidMount() {
    // const { initAsResizing: { enable, direction, event } } = this.props;
    // if (enable) this.refs.resizable.onResizeStart(direction, event);
  }

  componentWillReceiveProps({ x, y }) {
    // const { canUpdatePositionByParent } = this.props;
    // if (canUpdatePositionByParent && x !== this.state.x) this.setState({ x });
    // if (canUpdatePositionByParent && y !== this.state.y) this.setState({ y });
  }

  onResizeStart(dir, styleSize, clientSize, e) {
    this.setState({
      isDraggable: false,
      original: { x: this.state.x, y: this.state.y },
    });
    this.isResizing = true;
    this.props.onResizeStart(dir, styleSize, clientSize, e);
    e.stopPropagation();
  }

  onResize(dir, styleSize, clientSize, delta) {
    if (/left/i.test(dir)) {
      this.setState({ x: this.state.original.x - delta.width });
    }
    if (/top/i.test(dir)) {
      this.setState({ y: this.state.original.y - delta.height });
    }
    this.props.onResize(dir, styleSize, clientSize, delta);
  }

  onResizeStop(dir, styleSize, clientSize, delta) {
    this.setState({ isDraggable: true });
    this.isResizing = false;
    this.props.onResizeStop(dir, styleSize, clientSize, delta);
  }

  onDragStart(e, ui) {
    if (this.isResizing) return;
    this.props.onDragStart(e, ui);
  }

  onDrag(e, ui) {
    if (this.isResizing) return;
    const allowX = this.props.moveAxis === 'x';
    const allowY = this.props.moveAxis === 'y';
    const allowBoth = this.props.moveAxis === 'both';
    this.setState({
      x: allowX || allowBoth ? ui.position.left : this.state.x,
      y: allowY || allowBoth ? ui.position.top : this.state.y,
    });
    this.props.onDrag(e, ui);
  }

  onDragStop(e, ui) {
    if (this.isResizing) return;
    this.props.onDragStop(e, ui);
  }

  render() {
    const { className, style, onClick, onTouchStart,
            width, height, minWidth, minHeight, maxWidth, maxHeight,
            zIndex, bounds, moveAxis, dragHandlerClassName, lockAspectRatio,
            moveGrid, resizeGrid, onDoubleClick } = this.props;
    const { x, y } = this.state;
    return (
      <Draggable
        axis={moveAxis}
        zIndex={zIndex}
        start={{ x, y }}
        disabled={!this.state.isDraggable || this.props.moveAxis === 'none'}
        onStart={this.onDragStart}
        handle={dragHandlerClassName}
        onDrag={this.onDrag}
        onStop={this.onDragStop}
        bounds={bounds}
        grid={moveGrid}
        passCoordinate
        x={x}
        y={y}
      >

          <Resizable
            ref={c => { this.Resizable = c; }}
            onClick={onClick}
            onDoubleClick={onDoubleClick}
            onTouchStart={onTouchStart}
            onResizeStart={this.onResizeStart}
            onResize={this.onResize}
            onResizeStop={this.onResizeStop}
            width={width}
            height={height}
            minWidth={minWidth}
            minHeight={minHeight}
            maxWidth={maxWidth}
            maxHeight={maxHeight}
            customStyle={Object.assign(style, { boxSizing: 'border-box' })}
            customClass={className}
            isResizable={this.props.isResizable}
            handleStyle={this.props.resizerHandleStyle}
            grid={resizeGrid}
            lockAspectRatio={lockAspectRatio}
          >
            {this.props.children}
          </Resizable>

      </Draggable>
    );
  }
}
<commit_msg>Remove comment out<commit_after>import React, { Component, PropTypes } from 'react';
import Draggable from '@bokuweb/react-draggable-custom';
import Resizable from 'react-resizable-box';

const boxStyle = {
  width: 'auto',
  height: 'auto',
  cursor: 'move',
  position: 'absolute',
};

export default class ResizableAndMovable extends Component {
  static propTypes = {
    onResizeStart: PropTypes.func,
    onResize: PropTypes.func,
    onResizeStop: PropTypes.func,
    onDragStart: PropTypes.func,
    onDrag: PropTypes.func,
    onDragStop: PropTypes.func,
    className: PropTypes.string,
    style: PropTypes.object,
    children: PropTypes.any,
    onTouchStart: PropTypes.func,
    onClick: PropTypes.func,
    onDoubleClick: PropTypes.func,
    dragHandlerClassName: PropTypes.string,
    resizerHandleStyle: PropTypes.shape({
      top: PropTypes.object,
      right: PropTypes.object,
      bottom: PropTypes.object,
      left: PropTypes.object,
      topRight: PropTypes.object,
      bottomRight: PropTypes.object,
      bottomLeft: PropTypes.object,
      topLeft: PropTypes.object,
    }),
    isResizable: PropTypes.shape({
      top: PropTypes.bool,
      right: PropTypes.bool,
      bottom: PropTypes.bool,
      left: PropTypes.bool,
      topRight: PropTypes.bool,
      bottomRight: PropTypes.bool,
      bottomLeft: PropTypes.bool,
      topLeft: PropTypes.bool,
    }),
    width: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
    ]),
    height: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
    ]),
    minWidth: PropTypes.number,
    minHeight: PropTypes.number,
    maxWidth: PropTypes.number,
    maxHeight: PropTypes.number,
    moveAxis: PropTypes.oneOf(['x', 'y', 'both', 'none']),
    moveGrid: PropTypes.arrayOf(PropTypes.number),
    resizeGrid: PropTypes.arrayOf(PropTypes.number),
    bounds: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object,
    ]),
    x: PropTypes.number,
    y: PropTypes.number,
    zIndex: PropTypes.number,
    lockAspectRatio: PropTypes.bool,
  };

  static defaultProps = {
    x: 0,
    y: 0,
    width: 100,
    height: 100,
    zIndex: 100,
    className: '',
    dragHandlerClassName: '',
    isResizable: {
      top: true,
      right: true,
      bottom: true,
      left: true,
      topRight: true,
      bottomRight: true,
      bottomLeft: true,
      topLeft: true,
    },
    style: {},
    moveAxis: 'both',
    moveGrid: [1, 1],
    onClick: () => {},
    onTouchStart: () => {},
    onDragStart: () => {},
    onDrag: () => {},
    onDragStop: () => {},
    onResizeStart: () => {},
    onResize: () => {},
    onResizeStop: () => {},
    resizeGrid: [1, 1],
    lockAspectRatio: false,
  }

  constructor(props) {
    super(props);
    this.state = {
      isDraggable: true,
      isMounted: false,
      x: props.x,
      y: props.y,
      original: { x: props.x, y: props.y },
    };
    this.isResizing = false;
    this.onDragStart = this.onDragStart.bind(this);
    this.onDrag = this.onDrag.bind(this);
    this.onDragStop = this.onDragStop.bind(this);
    this.onResizeStart = this.onResizeStart.bind(this);
    this.onResize = this.onResize.bind(this);
    this.onResizeStop = this.onResizeStop.bind(this);
  }

  onResizeStart(dir, styleSize, clientSize, e) {
    this.setState({
      isDraggable: false,
      original: { x: this.state.x, y: this.state.y },
    });
    this.isResizing = true;
    this.props.onResizeStart(dir, styleSize, clientSize, e);
    e.stopPropagation();
  }

  onResize(dir, styleSize, clientSize, delta) {
    if (/left/i.test(dir)) {
      this.setState({ x: this.state.original.x - delta.width });
    }
    if (/top/i.test(dir)) {
      this.setState({ y: this.state.original.y - delta.height });
    }
    this.props.onResize(dir, styleSize, clientSize, delta);
  }

  onResizeStop(dir, styleSize, clientSize, delta) {
    this.setState({ isDraggable: true });
    this.isResizing = false;
    this.props.onResizeStop(dir, styleSize, clientSize, delta);
  }

  onDragStart(e, ui) {
    if (this.isResizing) return;
    this.props.onDragStart(e, ui);
  }

  onDrag(e, ui) {
    if (this.isResizing) return;
    const allowX = this.props.moveAxis === 'x';
    const allowY = this.props.moveAxis === 'y';
    const allowBoth = this.props.moveAxis === 'both';
    this.setState({
      x: allowX || allowBoth ? ui.position.left : this.state.x,
      y: allowY || allowBoth ? ui.position.top : this.state.y,
    });
    this.props.onDrag(e, ui);
  }

  onDragStop(e, ui) {
    if (this.isResizing) return;
    this.props.onDragStop(e, ui);
  }

  updateSize(size) {
    this.resizable.uploadSize(size);
  }

  updatePosition({ x, y }) {
    this.setState({ x, y });
  }

  render() {
    const { className, style, onClick, onTouchStart,
            width, height, minWidth, minHeight, maxWidth, maxHeight,
            zIndex, bounds, moveAxis, dragHandlerClassName, lockAspectRatio,
            moveGrid, resizeGrid, onDoubleClick } = this.props;
    const { x, y } = this.state;
    return (
      <Draggable
        axis={moveAxis}
        zIndex={zIndex}
        start={{ x, y }}
        disabled={!this.state.isDraggable || this.props.moveAxis === 'none'}
        onStart={this.onDragStart}
        handle={dragHandlerClassName}
        onDrag={this.onDrag}
        onStop={this.onDragStop}
        bounds={bounds}
        grid={moveGrid}
        passCoordinate
        x={x}
        y={y}
      >

          <Resizable
            ref={c => { this.resizable = c; }}
            onClick={onClick}
            onDoubleClick={onDoubleClick}
            onTouchStart={onTouchStart}
            onResizeStart={this.onResizeStart}
            onResize={this.onResize}
            onResizeStop={this.onResizeStop}
            width={width}
            height={height}
            minWidth={minWidth}
            minHeight={minHeight}
            maxWidth={maxWidth}
            maxHeight={maxHeight}
            customStyle={Object.assign(style, { boxSizing: 'border-box' })}
            customClass={className}
            isResizable={this.props.isResizable}
            handleStyle={this.props.resizerHandleStyle}
            grid={resizeGrid}
            lockAspectRatio={lockAspectRatio}
          >
            {this.props.children}
          </Resizable>

      </Draggable>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * Our Wholesale-Styleguide Component documentation
 * This is our Startpage for our component API
 * based on jsDocs
 * Here we should add more descriptions
 * Below are all components referenced
 *
 * - See {@link ws-header/ws-header.md|WSHeader}
 * - See {@link ws-date-picker/ws-date-picker.md|WSDatePicker}
 * - See {@link ws-dropdown/ws-dropdown.md|WSDropdown}
 * - See {@link ws-notification/ws-notification|WSNotification}
 * - See {@link ws-week-picker/ws-week-picker|WSWeekPicker}
 * @module WHStyleguide
 */

export {WSHeader} from './ws-header/ws-header';
export {WSDatePicker} from './ws-date-picker/ws-date-picker';
export {WSDropdown} from './ws-dropdown/ws-dropdown';
export {WSInlineEdit} from './ws-inline-edit/ws-inline-edit';
export {WSNotification} from './ws-notification/ws-notification';
export {WSWeekPicker} from './ws-week-picker/ws-week-picker';
<commit_msg>fixed jsDocs links in index<commit_after>/**
 * Our Wholesale-Styleguide Component documentation
 * This is our Startpage for our component API
 * based on jsDocs
 * Here we should add more descriptions
 * Below are all components referenced
 *
 * - See {@link ws-header/ws-header.md|WSHeader}
 * - See {@link ws-date-picker/ws-date-picker.md|WSDatePicker}
 * - See {@link ws-dropdown/ws-dropdown.md|WSDropdown}
 * - See {@link ws-notification/ws-notification.md|WSNotification}
 * - See {@link ws-week-picker/ws-week-picker.md|WSWeekPicker}
 * @module WHStyleguide
 */

export {WSHeader} from './ws-header/ws-header';
export {WSDatePicker} from './ws-date-picker/ws-date-picker';
export {WSDropdown} from './ws-dropdown/ws-dropdown';
export {WSInlineEdit} from './ws-inline-edit/ws-inline-edit';
export {WSNotification} from './ws-notification/ws-notification';
export {WSWeekPicker} from './ws-week-picker/ws-week-picker';
<|endoftext|>


<commit_before>class ListPlayer extends EventEmitter { // eslint-disable-line
  constructor (options = {}) {
    super()
    this.tracks = (options.tracks || []).map((t) => {
      if (typeof t === 'string') return { src: t }
      return t
    })
    this.loopTracks = options.loopTracks !== undefined ? options.loopTracks : true
    this.progressThroughTracks = options.progressThroughTracks !== undefined ? options.progressThroughTracks : true
    this.el = this._injectAudioElement()
    this.index = 0
    this._loadTrack()
    this.el.addEventListener('ended', () => {
      if (this.progressThroughTracks) {
        this.next()
        this.play()
      }
    })
    if (this.advanced) this._loadAudioContext()
  }

  play () {
    this.emit('play')
    this._loadTrack()
    return this.el.play()
  }

  pause () {
    this.emit('pause')
    return this.el.pause()
  }

  next () {
    this.emit('next')
    this.index++
    if (this.index > this.tracks.length - 1) {
      if (this.loopTracks) {
        this.index = 0
      } else {
        this.index--
        this.emit('error', 'you are on the last track')
      }
    }
    const _wasPlaying = this.playing()
    this._loadTrack()
    if (_wasPlaying) this.play()
  }

  prev () {
    this.emit('prev')
    this.index--
    if (this.index < 0) {
      if (this.loopTracks) {
        this.index = this.tracks.length - 1
      } else {
        this.index++
        this.emit('error', 'you are on the first track')
      }
    }
    const _wasPlaying = this.playing()
    this._loadTrack()
    if (_wasPlaying) this.play()
  }

  playing () {
    return !this.el.paused
  }

  seek (time) {
    if (!time) return this.el.currentTime
    this.emit('seek', time)
    this.el.currentTime = time
  }

  /**
   * Injects an audio element to the body and hides it.
   * @private
   */
  _injectAudioElement () {
    const el = document.createElement('audio')
    document.body.appendChild(el)
    el.style.display = 'none'
    return el
  }

  /**
   * Loads a track into the player
   * @private
   */
  _loadTrack () {
    if (this._loadedTrack === this.index) return
    if (this.tracks.length === 0) return
    this.el.innerHTML = ''

    this.currentTrack = this.tracks[this.index]
    const source = document.createElement('source')
    source.src = this.currentTrack.src
    source.type = 'audio/mp3'

    this.el.appendChild(source)
    this.el.load()
    this._loadedTrack = this.index
  }

  _loadAudioContext () {
    const AudioContext = window.AudioContext || window.webkitAudioContext
    if (!AudioContext) return this.emit('error', 'web audio api unsupported')
    this.ctx = new AudioContext()
    this.src = this.ctx.createMediaElementSource(this.el)
  }
}
<commit_msg>allow types other than audio/mp3<commit_after>class ListPlayer extends EventEmitter { // eslint-disable-line
  constructor (options = {}) {
    super()
    this.tracks = (options.tracks || []).map((t) => {
      if (typeof t === 'string') return { src: t }
      return t
    })
    this.loopTracks = options.loopTracks !== undefined ? options.loopTracks : true
    this.progressThroughTracks = options.progressThroughTracks !== undefined ? options.progressThroughTracks : true
    this.el = this._injectAudioElement()
    this.index = 0
    this._loadTrack()
    this.el.addEventListener('ended', () => {
      if (this.progressThroughTracks) {
        this.next()
        this.play()
      }
    })
    if (this.advanced) this._loadAudioContext()
  }

  play () {
    this.emit('play')
    this._loadTrack()
    return this.el.play()
  }

  pause () {
    this.emit('pause')
    return this.el.pause()
  }

  next () {
    this.emit('next')
    this.index++
    if (this.index > this.tracks.length - 1) {
      if (this.loopTracks) {
        this.index = 0
      } else {
        this.index--
        this.emit('error', 'you are on the last track')
      }
    }
    const _wasPlaying = this.playing()
    this._loadTrack()
    if (_wasPlaying) this.play()
  }

  prev () {
    this.emit('prev')
    this.index--
    if (this.index < 0) {
      if (this.loopTracks) {
        this.index = this.tracks.length - 1
      } else {
        this.index++
        this.emit('error', 'you are on the first track')
      }
    }
    const _wasPlaying = this.playing()
    this._loadTrack()
    if (_wasPlaying) this.play()
  }

  playing () {
    return !this.el.paused
  }

  seek (time) {
    if (!time) return this.el.currentTime
    this.emit('seek', time)
    this.el.currentTime = time
  }

  /**
   * Injects an audio element to the body and hides it.
   * @private
   */
  _injectAudioElement () {
    const el = document.createElement('audio')
    document.body.appendChild(el)
    el.style.display = 'none'
    return el
  }

  /**
   * Loads a track into the player
   * @private
   */
  _loadTrack () {
    if (this._loadedTrack === this.index) return
    if (this.tracks.length === 0) return
    this.el.innerHTML = ''

    this.currentTrack = this.tracks[this.index]
    const source = document.createElement('source')
    source.src = this.currentTrack.src
    source.type = this.currentTrack.type || 'audio/mp3'

    this.el.appendChild(source)
    this.el.load()
    this._loadedTrack = this.index
  }

  _loadAudioContext () {
    const AudioContext = window.AudioContext || window.webkitAudioContext
    if (!AudioContext) return this.emit('error', 'web audio api unsupported')
    this.ctx = new AudioContext()
    this.src = this.ctx.createMediaElementSource(this.el)
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*global $, VOICES, SAMPLE_TEXT */

'use strict';

$(document).ready(function() {
  var audio = $('.audio').get(0),
    textArea = $('#textArea');

  Object.keys(VOICES).forEach(function(key) {
    $('<option>', { value : key })
    .appendTo($('.select-voice'))
    .text(VOICES[key]);
  });

  function updateSampleText() {
    var lang = $('.select-voice').val().substr(0,5);
    $('#textArea').text(SAMPLE_TEXT[lang]);
  }
  $('.select-voice').change(updateSampleText);
  updateSampleText();

  // IE and Safari not supported disabled Speak button
  if ($('body').hasClass('ie') || $('body').hasClass('safari')) {
    $('.speak-button').prop('disabled', true);
  }

  if ($('.speak-button').prop('disabled')) {
    $('.ie-speak .arrow-box').show();
  }

  $('.audio').on('error', function () {
    $('.result').hide();
    $('.errorMgs').text('Error processing the request.');
    $('.errorMsg').css('color','red');
    $('.error').show();
  });

  $('.audio').on('loadeddata', function () {
    $('.result').show();
    $('.error').hide();
  });

  $('.download-button').click(function() {
    textArea.focus();
    if (validText(textArea.val())) {
      window.location.href = '/synthesize?download=true&' + $('form').serialize();
    }
  });

  $('.speak-button').click(function() {
    $('.result').hide();
    audio.pause();

    $('#textArea').focus();
    if (validText(textArea.val())) {
      audio.setAttribute('src','/synthesize?' + $('form').serialize());
    }
  });

  function validText(text) {
    $('.error').hide();
    $('.errorMsg').css('color','#5a5a5a');

    if ($.trim(text).length === 0) {
      $('.errorMsg').text('Please enter the text you would like to synthesize in the text window.');
      $('.errorMsg').css('color','#5a5a5a');
      $('.error').show();
      return false;
    }

    if (!containsAllLatin1(text)) {
      $('.errorMsg').text('Language not supported. Please use only ISO 8859 characters');
      $('.error').show();
      return false;
    }

    return true;
  }

  /**
   * Check that the text doesn't contains non latin-1 characters.
   * @param  String  The string to test
   * @return true if the string is latin-1
   */
  function containsAllLatin1(str) {
    return  /^[A-z\u00C0-\u00ff\s?@¿''\.,-\/#!$%\^&\*;:{}=\-_`~()0-9]+$/.test(str);
  }

});
<commit_msg>#1 fix for servlet path which is /<commit_after>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*global $, VOICES, SAMPLE_TEXT */

'use strict';

$(document).ready(function() {
  var audio = $('.audio').get(0),
    textArea = $('#textArea');

  Object.keys(VOICES).forEach(function(key) {
    $('<option>', { value : key })
    .appendTo($('.select-voice'))
    .text(VOICES[key]);
  });

  function updateSampleText() {
    var lang = $('.select-voice').val().substr(0,5);
    $('#textArea').text(SAMPLE_TEXT[lang]);
  }
  $('.select-voice').change(updateSampleText);
  updateSampleText();

  // IE and Safari not supported disabled Speak button
  if ($('body').hasClass('ie') || $('body').hasClass('safari')) {
    $('.speak-button').prop('disabled', true);
  }

  if ($('.speak-button').prop('disabled')) {
    $('.ie-speak .arrow-box').show();
  }

  $('.audio').on('error', function () {
    $('.result').hide();
    $('.errorMgs').text('Error processing the request.');
    $('.errorMsg').css('color','red');
    $('.error').show();
  });

  $('.audio').on('loadeddata', function () {
    $('.result').show();
    $('.error').hide();
  });

  $('.download-button').click(function() {
    textArea.focus();
    if (validText(textArea.val())) {
      window.location.href = '?download=true&' + $('form').serialize();
    }
  });

  $('.speak-button').click(function() {
    $('.result').hide();
    audio.pause();

    $('#textArea').focus();
    if (validText(textArea.val())) {
      audio.setAttribute('src','?&' + $('form').serialize());
    }
  });

  function validText(text) {
    $('.error').hide();
    $('.errorMsg').css('color','#5a5a5a');

    if ($.trim(text).length === 0) {
      $('.errorMsg').text('Please enter the text you would like to synthesize in the text window.');
      $('.errorMsg').css('color','#5a5a5a');
      $('.error').show();
      return false;
    }

    if (!containsAllLatin1(text)) {
      $('.errorMsg').text('Language not supported. Please use only ISO 8859 characters');
      $('.error').show();
      return false;
    }

    return true;
  }

  /**
   * Check that the text doesn't contains non latin-1 characters.
   * @param  String  The string to test
   * @return true if the string is latin-1
   */
  function containsAllLatin1(str) {
    return  /^[A-z\u00C0-\u00ff\s?@¿''\.,-\/#!$%\^&\*;:{}=\-_`~()0-9]+$/.test(str);
  }

});
<|endoftext|>


<commit_before>// Publish task
var path = require('path'),
  util = require('gulp-util'),
  gift = require('gift'),
  q = require('q');

function parseOptions(options) {
  options.folder = options.folder || 'dist';
  options.branch = options.branch || 'gh-pages';
  options.cname = options.cname || 'CNAME';
  options.commit = options.commit || 'Build '+(new Date());
  options.cwd = options.cwd || process.cwd();
  return options;
}

function buildBranch(options_) {
  var options, distRepoDir, distRepo, rootRepo, deferred;
  options = parseOptions(options_);
  deferred = q.defer();

  distRepoDir = path.join(options.cwd, options.folder);
  rootRepo = gift(options.cwd);

  // First, init repository in our dist dir
  gift.init(distRepoDir, function(err, repo) {

    // Check if repo, which may exist already, has any changes.
    repo.status(function(err, status) {
      if(status.clean) {
        util.log("BuildBranch:", util.colors.blue("No changes to be deployed."));
        deferred.resolve();

      }else{

        // Otherwise, add everything to new repo,
        repo.add('-A', function(err) {
          if(err) throw err;

          // Commit,
          repo.commit(options.commit, function(err) {

            // And fetch the branch from our root repo.
            rootRepo.remote_fetch('-f ' + options.folder + '/ master:' + options.branch, function(err) {
              if(err) throw err;

              deferred.resolve();
            });

          });
        });
      }
    });
  });

  return deferred.promise;
}

module.exports = buildBranch;
<commit_msg>Fetch deploy branch even if there are no changes.<commit_after>// Publish task
var path = require('path'),
  util = require('gulp-util'),
  gift = require('gift'),
  q = require('q'),
  distRepoDir, distRepo, rootRepo, deferred, options = {};

function parseOptions(options_) {
  options.folder = options_.folder || 'dist';
  options.branch = options_.branch || 'gh-pages';
  options.cname = options_.cname || 'CNAME';
  options.commit = options_.commit || 'Build '+(new Date());
  options.cwd = options_.cwd || process.cwd();
  return options;
}

function fetchFromRootRepo() {
  rootRepo.remote_fetch('-f ' + options.folder + '/ master:' + options.branch, function(err) {
    if(err) throw err;

    deferred.resolve();
  });
}

function buildBranch(options_) {
  parseOptions(options_);
  deferred = q.defer();

  distRepoDir = path.join(options.cwd, options.folder);
  rootRepo = gift(options.cwd);

  // First, init repository in our dist dir
  gift.init(distRepoDir, function(err, repo) {

    // Check if repo, which may exist already, has any changes.
    repo.status(function(err, status) {
      if(status.clean) {
        util.log("BuildBranch:", util.colors.blue("No changes to be deployed."));

        // Fetch it anyway, in cases where multiple deploy branches might be wanted.
        fetchFromRootRepo();

      }else{

        // Otherwise, add everything to new repo,
        repo.add('-A', function(err) {
          if(err) throw err;

          // Commit,
          repo.commit(options.commit, function(err) {
            // And fetch the branch from our root repo.
            fetchFromRootRepo();
          });
        });
      }
    });
  });

  return deferred.promise;
}

module.exports = buildBranch;
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var URI = require('urijs');
var _ = require('lodash');
var jsonCompat = require('json-schema-compatibility');
var HttpStatus = require('http-status-codes').getStatusText;
var jp = require('jsonpath');

exports.convert = function (raml) {
  //FIXME:
  //console.log(raml.documentation);

  var swagger = _.assign({
    swagger: '2.0',
    info: {
      title: raml.title,
      version: raml.version,
    },
    securityDefinitions: parseSecuritySchemes(raml.securitySchemes),
    paths: parseResources(raml.resources),
    definitions: parseSchemas(raml.schemas)
  }, parseBaseUri(raml));

  jp.apply(swagger.paths, '$..*.schema' , function (schema) {
    var result = schema;
    _.each(swagger.definitions, function (definition, name) {
      if (!_.isEqual(schema, definition))
        return;
      result = { $ref: '#/definitions/' + name};
    });
    return result;
  });

  if ('mediaType' in raml) {
    swagger.consumes = [raml.mediaType];
    swagger.produces = [raml.mediaType];
  }

  return swagger;
};

function parseBaseUri(raml) {
  var baseUri = raml.baseUri;

  if (!baseUri)
    return {};

  baseUri = baseUri.replace(/{version}/g, raml.version);
  //Don't support other URI templates right now.
  assert(baseUri.indexOf('{') == -1);

  baseUri = URI(baseUri);

  assert(!('baseUriParameters' in raml) ||
    _.isEqual(_.keys(raml.baseUriParameters), ['version']));
  assert(!('uriParameters' in raml));

  return {
    host: baseUri.host(),
    basePath: '/' + baseUri.pathname().replace(/^\/|\/$/, ''),
    schemes: parseProtocols(raml.protocols) || [baseUri.scheme()]
  };
}

function parseSecuritySchemes(ramlSecuritySchemes) {
  var srSecurityDefinitions = {};

  _.each(ramlSecuritySchemes, function (ramlSecurityArray) {
    _.each(ramlSecurityArray, function (ramlSecurityObj, name) {
      assert(ramlSecurityObj.type);

      //Swagger 2.0 doesn't support Oauth 1.0 so just skip it.
      //FIXME: add warning
      if (ramlSecurityObj.type === 'OAuth 1.0')
        return;

      var srType = {
        'OAuth 2.0': 'oauth2',
        'Basic Authentication': 'basic',
      }[ramlSecurityObj.type];
      assert(srType);

      var srSecurity = {
        type: srType,
        description: ramlSecurityObj.description,
      };

      if (srType !== 'oauth2') {
        srSecurityDefinitions[name] = srSecurity;
        return;
      }

      var ramlSettings = ramlSecurityObj.settings;
      _.assign(srSecurity, {
        authorizationUrl: ramlSettings.authorizationUri,
        tokenUrl: ramlSettings.accessTokenUri,
        scopes: _.transform(ramlSettings.scopes, function (result, name) {
          result[name] = '';
        }, {})
      });

      var ramlFlows = ramlSettings.authorizationGrants;
      _.each(ramlFlows, function (ramlFlow) {
         var srFlowSecurity = _.clone(srSecurity);
         var srFlow = srFlowSecurity.flow = {
           'code': 'accessCode',
           'token': 'implicit',
           'owner': 'password',
           'credentials': 'application'
         }[ramlFlow];

         if (srFlow === 'password' || srFlow === 'application')
           delete srFlowSecurity.authorizationUrl;

         if (srFlow === 'implicit')
           delete srFlowSecurity.tokenUrl;

         var fullName = name;
         if (_.size(ramlFlows) > 1)
           fullName = name + '_' + srFlowSecurity.flow;

         srSecurityDefinitions[fullName] = srFlowSecurity;
      });
    });
  });
  return srSecurityDefinitions;
}

function parseSchemas(ramlSchemas) {
  return _.reduce(ramlSchemas, function (definitions, ramlSchemasMap) {
    return _.assign(definitions, ramlSchemasMap, function (dummy, ramlSchema) {
      return convertSchema(ramlSchema);
    });
  }, {});
}

function parseProtocols(ramlProtocols) {
  return _.map(ramlProtocols, function (str) {
    return str.toLowerCase();
  });
}

function parseResources(ramlResources, srPathParameters) {
  var srPaths = {};

  _.each(ramlResources, function (ramlResource) {

    //assert(!('displayName' in ramlResource));
    assert(!('description' in ramlResource && ramlResource.description !== ''));
    assert(!('baseUriParameters' in ramlResource));

    var resourceName = ramlResource.relativeUri;
    assert(resourceName);

    var srResourceParameters = (srPathParameters || []).concat(
      parseParametersList(ramlResource.uriParameters, 'path'));

    var srMethods = parseMethodList(ramlResource.methods, srResourceParameters);
    if (!_.isEmpty(srMethods))
      srPaths[resourceName] = srMethods;

    var srSubPaths = parseResources(ramlResource.resources, srResourceParameters);
    _.each(srSubPaths, function (subResource, subResourceName) {
      srPaths[resourceName + subResourceName] = subResource;
    });
  });
  return srPaths;
}

function parseMethodList(ramlMethods, srPathParameters) {
  var srMethods = {};
  _.each(ramlMethods, function (ramlMethod) {
    var srMethod = parseMethod(ramlMethod);
    if (!_.isEmpty(srPathParameters))
      srMethod.parameters = srPathParameters.concat(srMethod.parameters);
    srMethods[ramlMethod.method] = srMethod;
  });
  return srMethods;
}

function parseMethod(ramlMethod) {
  //FIXME:
  //assert(!('protocols' in data));
  //assert(!('securedBy' in data));

  var srMethod = {
    description: ramlMethod.description,
  };

  var srParameters = parseParametersList(ramlMethod.queryParameters, 'query');
  srParameters = srParameters.concat(
    parseParametersList(ramlMethod.headers, 'header'));

  if (!_.isEmpty(srParameters))
    srMethod.parameters = srParameters;

  parseBody(ramlMethod.body, srMethod);

  parseResponses(ramlMethod, srMethod);

  return srMethod;
}

function parseResponses(ramlMethod, srMethod) {
  var ramlResponces = ramlMethod.responses;
  if (_.isEmpty(ramlResponces)) {
    return {
      200: { description: HttpStatus(200) }
    };
  }

  srMethod.responses = {};
  _.each(ramlResponces, function (ramlResponce, httpCode) {
    var defaultDescription = HttpStatus(parseInt(httpCode));
    var srResponse = srMethod.responses[httpCode] = {
      description: _.get(ramlResponce, 'description') || defaultDescription
    };

    if (!_.has(ramlResponce, 'body'))
      return;

    var jsonMIME = 'application/json';
    var produces = _.without(_.keys(ramlResponce.body), jsonMIME);
    //TODO: types could have examples.
    if (!_.isEmpty(produces))
      srMethod.produces = produces;

    var jsonSchema = _.get(ramlResponce.body, jsonMIME);
    if (!_.isUndefined(jsonSchema)) {
      //TODO:
      //assert(!_.has(jsonSchema, 'example'));
      srResponse.schema = parseJsonPayload(jsonSchema);
    }
  });
}

function parseParametersList(params, inValue) {
  assert(_.isUndefined(params) || _.isPlainObject(params));

  return _.map(params, function (value, key) {
     assert(!_.has(value, 'repeat'));
     //FIXME:
     //assert(!_.has(value, 'example'));
     //assert(!_.has(value, 'displayName'));
     assert(_.has(value, 'type') &&
       ['date', 'string', 'number', 'integer', 'boolean'].indexOf(value.type) !== -1);

     var srParameter = {
       name: key,
       in: inValue,
       description: value.description,
       required: value.required,
       type: value.type,
       enum: value.enum,
       default: value.default,
       maximum: value.maximum,
       minimum: value.minimum,
       maxLength: value.maxLength,
       minLength: value.minLength,
       pattern: value.pattern
     };

     if (srParameter.type === 'date') {
       srParameter.type = 'string';
       srParameter.format = 'date';
     }

     return srParameter;
  });
}

function parseBody(ramlBody, srMethod) {
  if (!ramlBody)
    return;

  var keys = _.keys(ramlBody)
  assert(!_.has(keys, 'application/x-www-form-urlencoded'));
  assert(!_.has(keys, 'multipart/form-data'));
  //TODO: All parsers of RAML MUST be able to interpret ... and XML Schema
  var jsonMIME = 'application/json';

  var consumes = _.without(keys, jsonMIME);
  //TODO: types could have examples.
  if (!_.isEmpty(consumes))
    srMethod.consumes = consumes;

  if (_.indexOf(keys, jsonMIME) === -1)
    return;

  if (_.isUndefined(srMethod.parameters))
    srMethod.parameters = [];

  srMethod.parameters.push({
    //FIXME: check if name is used;
    name: 'body',
    in: 'body',
    required: true,
    //TODO: copy example
    schema: parseJsonPayload(ramlBody[jsonMIME])
  });
}

function parseJsonPayload(data)
{
  assert(_.has(data, 'schema'));

  return convertSchema(data.schema);
}

function convertSchema(schema) {
  if (_.isUndefined(schema))
    return;

  assert(_.isString(schema));

  var schema = JSON.parse(schema);

  delete schema.id;

  //FIXME:
  assert.equal(schema.$schema || schema[''], 'http://json-schema.org/draft-03/schema');

  schema = jsonCompat.v4(schema);
  delete schema.$schema;
  delete schema[''];

  //Add '#/definitions/' prefix to all internal refs
  jp.apply(schema, '$..*["$ref"]' , function (ref) {
    return '#/definitions/' + ref;
  });

  //Fixes for common mistakes in RAML 0.8

  // Fix case when instead of 'additionalProperties' schema put in following wrappers:
  // {
  //   "type": "object",
  //   "": [{
  //     ...
  //   }]
  // }
  // or
  // {
  //   "type": "object",
  //   "properties": {
  //     "": [{
  //       ...
  //     }]
  //   }
  // }

  _.each(jp.nodes(schema, '$..*[""]'), function(result) {
    var value = result.value;
    var path = result.path;

    if (!_.isArray(value) || _.size(value) !== 1 || !_.isPlainObject(value[0]))
      return;

    path = _.dropRight(path);
    var parent = jp.value(schema, jp.stringify(path));
    delete parent[''];

    if (_.isEmpty(parent) && _.last(path) === 'properties') {
      parent = jp.value(schema, jp.stringify(_.dropRight(path)));
      delete parent.properties;
    }

    assert(parent.type === 'object');
    parent.additionalProperties = value[0];
  });

  // Fix case when arrays definition wrapped with array, like that:
  // [{
  //   "type": "array",
  //   ...
  // }]

  _.each(jp.nodes(schema, '$..properties.*[0]'), function(result) {
    var path = _.dropRight(result.path);
    var value = jp.value(schema, jp.stringify(path));

    if (_.size(value) !== 1 || !_.isArray(value) || value[0].type !== 'array')
      return;

    var parent = jp.value(schema, jp.stringify(_.dropRight(path)));
    parent[_.last(path)] = value[0];
  });

  // Fix case then 'items' value is empty array.
  jp.apply(schema, '$..*[?(@.type === "array" && @.items.length === 0)]', function(schema) {
    schema.items = {};
  });

  return schema;
}
<commit_msg>Temporary disable check for 'descriptions' inside resources<commit_after>'use strict';

var assert = require('assert');
var URI = require('urijs');
var _ = require('lodash');
var jsonCompat = require('json-schema-compatibility');
var HttpStatus = require('http-status-codes').getStatusText;
var jp = require('jsonpath');

exports.convert = function (raml) {
  //FIXME:
  //console.log(raml.documentation);

  var swagger = _.assign({
    swagger: '2.0',
    info: {
      title: raml.title,
      version: raml.version,
    },
    securityDefinitions: parseSecuritySchemes(raml.securitySchemes),
    paths: parseResources(raml.resources),
    definitions: parseSchemas(raml.schemas)
  }, parseBaseUri(raml));

  jp.apply(swagger.paths, '$..*.schema' , function (schema) {
    var result = schema;
    _.each(swagger.definitions, function (definition, name) {
      if (!_.isEqual(schema, definition))
        return;
      result = { $ref: '#/definitions/' + name};
    });
    return result;
  });

  if ('mediaType' in raml) {
    swagger.consumes = [raml.mediaType];
    swagger.produces = [raml.mediaType];
  }

  return swagger;
};

function parseBaseUri(raml) {
  var baseUri = raml.baseUri;

  if (!baseUri)
    return {};

  baseUri = baseUri.replace(/{version}/g, raml.version);
  //Don't support other URI templates right now.
  assert(baseUri.indexOf('{') == -1);

  baseUri = URI(baseUri);

  assert(!('baseUriParameters' in raml) ||
    _.isEqual(_.keys(raml.baseUriParameters), ['version']));
  assert(!('uriParameters' in raml));

  return {
    host: baseUri.host(),
    basePath: '/' + baseUri.pathname().replace(/^\/|\/$/, ''),
    schemes: parseProtocols(raml.protocols) || [baseUri.scheme()]
  };
}

function parseSecuritySchemes(ramlSecuritySchemes) {
  var srSecurityDefinitions = {};

  _.each(ramlSecuritySchemes, function (ramlSecurityArray) {
    _.each(ramlSecurityArray, function (ramlSecurityObj, name) {
      assert(ramlSecurityObj.type);

      //Swagger 2.0 doesn't support Oauth 1.0 so just skip it.
      //FIXME: add warning
      if (ramlSecurityObj.type === 'OAuth 1.0')
        return;

      var srType = {
        'OAuth 2.0': 'oauth2',
        'Basic Authentication': 'basic',
      }[ramlSecurityObj.type];
      assert(srType);

      var srSecurity = {
        type: srType,
        description: ramlSecurityObj.description,
      };

      if (srType !== 'oauth2') {
        srSecurityDefinitions[name] = srSecurity;
        return;
      }

      var ramlSettings = ramlSecurityObj.settings;
      _.assign(srSecurity, {
        authorizationUrl: ramlSettings.authorizationUri,
        tokenUrl: ramlSettings.accessTokenUri,
        scopes: _.transform(ramlSettings.scopes, function (result, name) {
          result[name] = '';
        }, {})
      });

      var ramlFlows = ramlSettings.authorizationGrants;
      _.each(ramlFlows, function (ramlFlow) {
         var srFlowSecurity = _.clone(srSecurity);
         var srFlow = srFlowSecurity.flow = {
           'code': 'accessCode',
           'token': 'implicit',
           'owner': 'password',
           'credentials': 'application'
         }[ramlFlow];

         if (srFlow === 'password' || srFlow === 'application')
           delete srFlowSecurity.authorizationUrl;

         if (srFlow === 'implicit')
           delete srFlowSecurity.tokenUrl;

         var fullName = name;
         if (_.size(ramlFlows) > 1)
           fullName = name + '_' + srFlowSecurity.flow;

         srSecurityDefinitions[fullName] = srFlowSecurity;
      });
    });
  });
  return srSecurityDefinitions;
}

function parseSchemas(ramlSchemas) {
  return _.reduce(ramlSchemas, function (definitions, ramlSchemasMap) {
    return _.assign(definitions, ramlSchemasMap, function (dummy, ramlSchema) {
      return convertSchema(ramlSchema);
    });
  }, {});
}

function parseProtocols(ramlProtocols) {
  return _.map(ramlProtocols, function (str) {
    return str.toLowerCase();
  });
}

function parseResources(ramlResources, srPathParameters) {
  var srPaths = {};

  _.each(ramlResources, function (ramlResource) {

    //FIXME: convert or create warning
    //assert(!('displayName' in ramlResource));
    //assert(!('description' in ramlResource && ramlResource.description !== ''));
    assert(!('baseUriParameters' in ramlResource));

    var resourceName = ramlResource.relativeUri;
    assert(resourceName);

    var srResourceParameters = (srPathParameters || []).concat(
      parseParametersList(ramlResource.uriParameters, 'path'));

    var srMethods = parseMethodList(ramlResource.methods, srResourceParameters);
    if (!_.isEmpty(srMethods))
      srPaths[resourceName] = srMethods;

    var srSubPaths = parseResources(ramlResource.resources, srResourceParameters);
    _.each(srSubPaths, function (subResource, subResourceName) {
      srPaths[resourceName + subResourceName] = subResource;
    });
  });
  return srPaths;
}

function parseMethodList(ramlMethods, srPathParameters) {
  var srMethods = {};
  _.each(ramlMethods, function (ramlMethod) {
    var srMethod = parseMethod(ramlMethod);
    if (!_.isEmpty(srPathParameters))
      srMethod.parameters = srPathParameters.concat(srMethod.parameters);
    srMethods[ramlMethod.method] = srMethod;
  });
  return srMethods;
}

function parseMethod(ramlMethod) {
  //FIXME:
  //assert(!('protocols' in data));
  //assert(!('securedBy' in data));

  var srMethod = {
    description: ramlMethod.description,
  };

  var srParameters = parseParametersList(ramlMethod.queryParameters, 'query');
  srParameters = srParameters.concat(
    parseParametersList(ramlMethod.headers, 'header'));

  if (!_.isEmpty(srParameters))
    srMethod.parameters = srParameters;

  parseBody(ramlMethod.body, srMethod);

  parseResponses(ramlMethod, srMethod);

  return srMethod;
}

function parseResponses(ramlMethod, srMethod) {
  var ramlResponces = ramlMethod.responses;
  if (_.isEmpty(ramlResponces)) {
    return {
      200: { description: HttpStatus(200) }
    };
  }

  srMethod.responses = {};
  _.each(ramlResponces, function (ramlResponce, httpCode) {
    var defaultDescription = HttpStatus(parseInt(httpCode));
    var srResponse = srMethod.responses[httpCode] = {
      description: _.get(ramlResponce, 'description') || defaultDescription
    };

    if (!_.has(ramlResponce, 'body'))
      return;

    var jsonMIME = 'application/json';
    var produces = _.without(_.keys(ramlResponce.body), jsonMIME);
    //TODO: types could have examples.
    if (!_.isEmpty(produces))
      srMethod.produces = produces;

    var jsonSchema = _.get(ramlResponce.body, jsonMIME);
    if (!_.isUndefined(jsonSchema)) {
      //TODO:
      //assert(!_.has(jsonSchema, 'example'));
      srResponse.schema = parseJsonPayload(jsonSchema);
    }
  });
}

function parseParametersList(params, inValue) {
  assert(_.isUndefined(params) || _.isPlainObject(params));

  return _.map(params, function (value, key) {
     assert(!_.has(value, 'repeat'));
     //FIXME:
     //assert(!_.has(value, 'example'));
     //assert(!_.has(value, 'displayName'));
     assert(_.has(value, 'type') &&
       ['date', 'string', 'number', 'integer', 'boolean'].indexOf(value.type) !== -1);

     var srParameter = {
       name: key,
       in: inValue,
       description: value.description,
       required: value.required,
       type: value.type,
       enum: value.enum,
       default: value.default,
       maximum: value.maximum,
       minimum: value.minimum,
       maxLength: value.maxLength,
       minLength: value.minLength,
       pattern: value.pattern
     };

     if (srParameter.type === 'date') {
       srParameter.type = 'string';
       srParameter.format = 'date';
     }

     return srParameter;
  });
}

function parseBody(ramlBody, srMethod) {
  if (!ramlBody)
    return;

  var keys = _.keys(ramlBody)
  assert(!_.has(keys, 'application/x-www-form-urlencoded'));
  assert(!_.has(keys, 'multipart/form-data'));
  //TODO: All parsers of RAML MUST be able to interpret ... and XML Schema
  var jsonMIME = 'application/json';

  var consumes = _.without(keys, jsonMIME);
  //TODO: types could have examples.
  if (!_.isEmpty(consumes))
    srMethod.consumes = consumes;

  if (_.indexOf(keys, jsonMIME) === -1)
    return;

  if (_.isUndefined(srMethod.parameters))
    srMethod.parameters = [];

  srMethod.parameters.push({
    //FIXME: check if name is used;
    name: 'body',
    in: 'body',
    required: true,
    //TODO: copy example
    schema: parseJsonPayload(ramlBody[jsonMIME])
  });
}

function parseJsonPayload(data)
{
  assert(_.has(data, 'schema'));

  return convertSchema(data.schema);
}

function convertSchema(schema) {
  if (_.isUndefined(schema))
    return;

  assert(_.isString(schema));

  var schema = JSON.parse(schema);

  delete schema.id;

  //FIXME:
  assert.equal(schema.$schema || schema[''], 'http://json-schema.org/draft-03/schema');

  schema = jsonCompat.v4(schema);
  delete schema.$schema;
  delete schema[''];

  //Add '#/definitions/' prefix to all internal refs
  jp.apply(schema, '$..*["$ref"]' , function (ref) {
    return '#/definitions/' + ref;
  });

  //Fixes for common mistakes in RAML 0.8

  // Fix case when instead of 'additionalProperties' schema put in following wrappers:
  // {
  //   "type": "object",
  //   "": [{
  //     ...
  //   }]
  // }
  // or
  // {
  //   "type": "object",
  //   "properties": {
  //     "": [{
  //       ...
  //     }]
  //   }
  // }

  _.each(jp.nodes(schema, '$..*[""]'), function(result) {
    var value = result.value;
    var path = result.path;

    if (!_.isArray(value) || _.size(value) !== 1 || !_.isPlainObject(value[0]))
      return;

    path = _.dropRight(path);
    var parent = jp.value(schema, jp.stringify(path));
    delete parent[''];

    if (_.isEmpty(parent) && _.last(path) === 'properties') {
      parent = jp.value(schema, jp.stringify(_.dropRight(path)));
      delete parent.properties;
    }

    assert(parent.type === 'object');
    parent.additionalProperties = value[0];
  });

  // Fix case when arrays definition wrapped with array, like that:
  // [{
  //   "type": "array",
  //   ...
  // }]

  _.each(jp.nodes(schema, '$..properties.*[0]'), function(result) {
    var path = _.dropRight(result.path);
    var value = jp.value(schema, jp.stringify(path));

    if (_.size(value) !== 1 || !_.isArray(value) || value[0].type !== 'array')
      return;

    var parent = jp.value(schema, jp.stringify(_.dropRight(path)));
    parent[_.last(path)] = value[0];
  });

  // Fix case then 'items' value is empty array.
  jp.apply(schema, '$..*[?(@.type === "array" && @.items.length === 0)]', function(schema) {
    schema.items = {};
  });

  return schema;
}
<|endoftext|>


<commit_before>import { curry } from 'ramda'
import chai, { expect } from 'chai'
import asPromised from 'chai-as-promised'
chai.use(asPromised)

/**
 * Curryable function to check primitive type equality
 *
 * @param  {String} type  primitive type to check for
 * @param  {*}      val   value of any type
 * @return {undefined}
 */
const shouldBeA = curry(
  (type, val) => {
    it(`should be an ${type}`, () => {
      expect(val).to.be.an(type)
    })
  }
)

/**
 * Curryable function to check equality against any value
 *
 * @param  {*}  testVal value to check against
 * @param  {*}  val     value to check
 * @return {undefined}
 */
const shouldEqual = curry(
  (testVal, val) => {
    it(`should equal ${testVal}`, () => {
      expect(val).to.equal(testVal)
    })
  }
)

/**
 * Curryable function to check that val is not of a given falsey type
 *
 * @param  {String}   falseyType  a supported mocha functinon of `not.be...`
 * @param  {*}        value under test
 * @return {undefined}
 */
const shouldNotBeFalseyFamily = curry(
  (falseyType, isPromise, val) => {
    it(`should not be ${falseyType}`, () => {
      if (isPromise) {
        expect(val).to.eventually.not.be[falseyType]
      } else {
        expect(val).to.not.be[falseyType]
      }
    })
  }
)

/**
 * Curryable function to check that val is of a given falsey type
 *
 * @param  {String}   falseyType  a supported mocha functinon of `not.be...`
 * @param  {*}        value under test
 * @return {undefined}
 */
const shouldBeFalseyFamily = curry(
  (falseyType, isPromise, val) => {
    it(`should not be ${falseyType}`, () => {
      if (isPromise) {
        expect(val).to.eventually.be[falseyType]
      } else {
        expect(val).to.be[falseyType]
      }
    })
  }
)

/**
 * Returns a function that return the result of invoking the given function
 * with the given value
 *
 * @param  {Function} func  function to invoke`
 * @param  {*}        val   value to invoke the function with
 * @return {Function}
 */
const invoke = (func, val) => () => func(val);

/**
 * Curryable function to check whether a function given a certain value
 * will throw a certain error.
 *
 * Can be partially applied in order to check multiple error types
 * or multiple arguments with a more concise syntax
 *
 * @param  {Function} func  function to invoke
 * @param  {*}        val   arg to invoke function with
 * @param  {Error}    err   error type like 'RefereceError' or 'TypeError'
 * @return {undefined}
 */
const shouldThrow = curry(
  (func, val, err) => {
    it(`should throw an ${err} error`, () => {
      expect(invoke(func, val)).to.throw(err)
    });
  }
)

/**
 * Curryable function to check whether a function given a certain value
 * will NOT throw a certain error.
 *
 * Can be partially applied in order to check multiple error types
 * or multiple arguments with a more concise syntax
 *
 * @param  {Function} func  function to invoke
 * @param  {*}        val   arg to invoke function with
 * @return {undefined}
 */
const shouldNotThrow = curry(
  (func, val) => {
    it(`should not throw an error`, () => {
      expect(invoke(func, val)).to.not.throw()
    });
  }
)

export const shouldBeAnObject = shouldBeA('object')
export const shouldBeAnArray = shouldBeA('array')
export const shouldBeABoolean = shouldBeA('boolean')
export const shouldBeAString = shouldBeA('string')
export const shouldBeANumber = shouldBeA('number')
export const shouldBeAnError = shouldBeA('error')
export const shouldBeAFunction = shouldBeA('function')

export const shouldNotBeUndefined = shouldNotBeFalseyFamily('undefined', false)
export const shouldNotBeNull = shouldNotBeFalseyFamily('null', false)
export const shouldNotBeEmpty = shouldNotBeFalseyFamily('empty', false)
export const shouldBeUndefined = shouldBeFalseyFamily('undefined', false)
export const shouldBeNull = shouldBeFalseyFamily('null', false)
export const shouldBeEmpty = shouldBeFalseyFamily('empty', false)

export const shouldNotBeUndefinedAsync = shouldNotBeFalseyFamily('undefined', true)
export const shouldNotBeNullAsync = shouldNotBeFalseyFamily('null', true)
export const shouldNotBeEmptyAsync = shouldNotBeFalseyFamily('empty', true)
export const shouldBeUndefinedAsync = shouldBeFalseyFamily('undefined', true)
export const shouldBeNullAsync = shouldBeFalseyFamily('null', true)
export const shouldBeEmptyAsync = shouldBeFalseyFamily('empty', true)

/**
 * Creates a test with assertions to check for null, undefined, and empty values
 *
 * @param  {*}        val   value under test
 * @param  {Boolean}  async `optional` pass true if testing a promise resolution
 * @return {undefined}
 */
export function testIfExists(val, async) {
  if (async) {
    shouldNotBeNullAsync(val)
    shouldNotBeUndefinedAsync(val)
    shouldNotBeEmptyAsync(val)
  } else {
    shouldNotBeNull(val)
    shouldNotBeUndefined(val)
    shouldNotBeEmpty(val)
  }
}

/**
 * Used to express groups of tests as arrays when a number of similar test cases
 * are being written
 *
 * @param  {Array}    [description, testVal, expected]  destuctured respectively
 * @param  {Function} func                              function under test
 * @return {undefined}
 */
export function testSet([description, testVal, expected], func) {
  describe(description, () => {
    const result = func(testVal)

    it(`should return ${expected}`, () => {
      expect(result).to.equal(expected)
    })
  })
}
<commit_msg>Exporting bug in last version<commit_after>import { curry } from 'ramda'
import chai, { expect } from 'chai'
import asPromised from 'chai-as-promised'
chai.use(asPromised)

/**
 * Curryable function to check primitive type equality
 *
 * @param  {String} type  primitive type to check for
 * @param  {*}      val   value of any type
 * @return {undefined}
 */
const shouldBeA = curry(
  (type, val) => {
    it(`should be an ${type}`, () => {
      expect(val).to.be.an(type)
    })
  }
)

/**
 * Curryable function to check equality against any value
 *
 * @param  {*}  testVal value to check against
 * @param  {*}  val     value to check
 * @return {undefined}
 */
const shouldEqual = curry(
  (testVal, val) => {
    it(`should equal ${testVal}`, () => {
      expect(val).to.equal(testVal)
    })
  }
)

/**
 * Curryable function to check that val is not of a given falsey type
 *
 * @param  {String}   falseyType  a supported mocha functinon of `not.be...`
 * @param  {*}        value under test
 * @return {undefined}
 */
const shouldNotBeFalseyFamily = curry(
  (falseyType, isPromise, val) => {
    it(`should not be ${falseyType}`, () => {
      if (isPromise) {
        expect(val).to.eventually.not.be[falseyType]
      } else {
        expect(val).to.not.be[falseyType]
      }
    })
  }
)

/**
 * Curryable function to check that val is of a given falsey type
 *
 * @param  {String}   falseyType  a supported mocha functinon of `not.be...`
 * @param  {*}        value under test
 * @return {undefined}
 */
const shouldBeFalseyFamily = curry(
  (falseyType, isPromise, val) => {
    it(`should not be ${falseyType}`, () => {
      if (isPromise) {
        expect(val).to.eventually.be[falseyType]
      } else {
        expect(val).to.be[falseyType]
      }
    })
  }
)

/**
 * Returns a function that return the result of invoking the given function
 * with the given value
 *
 * @param  {Function} func  function to invoke`
 * @param  {*}        val   value to invoke the function with
 * @return {Function}
 */
const invoke = (func, val) => () => func(val);

/**
 * Curryable function to check whether a function given a certain value
 * will throw a certain error.
 *
 * Can be partially applied in order to check multiple error types
 * or multiple arguments with a more concise syntax
 *
 * @param  {Function} func  function to invoke
 * @param  {*}        val   arg to invoke function with
 * @param  {Error}    err   error type like 'RefereceError' or 'TypeError'
 * @return {undefined}
 */
export const shouldThrow = curry(
  (func, val, err) => {
    it(`should throw an ${err} error`, () => {
      expect(invoke(func, val)).to.throw(err)
    });
  }
)

/**
 * Curryable function to check whether a function given a certain value
 * will NOT throw a certain error.
 *
 * Can be partially applied in order to check multiple error types
 * or multiple arguments with a more concise syntax
 *
 * @param  {Function} func  function to invoke
 * @param  {*}        val   arg to invoke function with
 * @return {undefined}
 */
export const shouldNotThrow = curry(
  (func, val) => {
    it(`should not throw an error`, () => {
      expect(invoke(func, val)).to.not.throw()
    });
  }
)

export const shouldBeAnObject = shouldBeA('object')
export const shouldBeAnArray = shouldBeA('array')
export const shouldBeABoolean = shouldBeA('boolean')
export const shouldBeAString = shouldBeA('string')
export const shouldBeANumber = shouldBeA('number')
export const shouldBeAnError = shouldBeA('error')
export const shouldBeAFunction = shouldBeA('function')

export const shouldNotBeUndefined = shouldNotBeFalseyFamily('undefined', false)
export const shouldNotBeNull = shouldNotBeFalseyFamily('null', false)
export const shouldNotBeEmpty = shouldNotBeFalseyFamily('empty', false)
export const shouldBeUndefined = shouldBeFalseyFamily('undefined', false)
export const shouldBeNull = shouldBeFalseyFamily('null', false)
export const shouldBeEmpty = shouldBeFalseyFamily('empty', false)

export const shouldNotBeUndefinedAsync = shouldNotBeFalseyFamily('undefined', true)
export const shouldNotBeNullAsync = shouldNotBeFalseyFamily('null', true)
export const shouldNotBeEmptyAsync = shouldNotBeFalseyFamily('empty', true)
export const shouldBeUndefinedAsync = shouldBeFalseyFamily('undefined', true)
export const shouldBeNullAsync = shouldBeFalseyFamily('null', true)
export const shouldBeEmptyAsync = shouldBeFalseyFamily('empty', true)

/**
 * Creates a test with assertions to check for null, undefined, and empty values
 *
 * @param  {*}        val   value under test
 * @param  {Boolean}  async `optional` pass true if testing a promise resolution
 * @return {undefined}
 */
export function testIfExists(val, async) {
  if (async) {
    shouldNotBeNullAsync(val)
    shouldNotBeUndefinedAsync(val)
    shouldNotBeEmptyAsync(val)
  } else {
    shouldNotBeNull(val)
    shouldNotBeUndefined(val)
    shouldNotBeEmpty(val)
  }
}

/**
 * Used to express groups of tests as arrays when a number of similar test cases
 * are being written
 *
 * @param  {Array}    [description, testVal, expected]  destuctured respectively
 * @param  {Function} func                              function under test
 * @return {undefined}
 */
export function testSet([description, testVal, expected], func) {
  describe(description, () => {
    const result = func(testVal)

    it(`should return ${expected}`, () => {
      expect(result).to.equal(expected)
    })
  })
}
<|endoftext|>


<commit_before>const React = require('react');
const isWebpackBundle = require('is-webpack-bundle');
const webpackRequireWeak = require('webpack-require-weak');
const {inspect} = require('import-inspector');

function capture(fn) {
  let reported = [];
  let stopInspecting = inspect(metadata => reported.push(metadata));
  let promise = fn();
  stopInspecting();
  return {promise, reported};
}

function load(loader) {
  let {promise, reported} = capture(() => {
    return loader();
  });

  if (reported.length > 1) {
    throw new Error('react-loadable cannot handle more than one import() in each loader');
  }

  let state = {
    loading: true,
    loaded: null,
    error: null
  };

  let metadata = reported[0] || {};

  try {
    if (isWebpackBundle) {
      if (typeof metadata.webpackRequireWeakId === 'function') {
        state.loading = false;
        state.loaded = webpackRequireWeak(metadata.webpackRequireWeakId());
      }
    } else {
      if (typeof metadata.serverSideRequirePath === 'string') {
        state.loading = false;
        state.loaded = module.require(metadata.serverSideRequirePath);
      }
    }
  } catch (err) {
    state.error = err;
  }

  state.promise = promise.then(loaded => {
    state.loading = false;
    state.loaded = loaded;
    return loaded;
  }).catch(err => {
    state.loading = false;
    state.error = err;
    throw err;
  });

  return state;
}

function loadMap(obj) {
  let state = {
    loading: false,
    loaded: {},
    error: null
  };

  let promises = [];

  try {
    Object.keys(obj).forEach(key => {
      let result = load(obj[key]);

      if (!result.loading) {
        state.loaded[key] = result.loaded;
        state.error = result.error;
      } else {
        state.loading = true;
      }

      promises.push(result.promise);

      result.promise.then(res => {
        state.loaded[key] = res;
      }).catch(err => {
        state.error = err;
      });
    });
  } catch (err) {
    error = err;
  }

  state.promise = Promise.all(promises).then(res => {
    state.loading = false;
    return res;
  }).catch(err => {
    state.loading = false;
    throw err;
  });

  return state;
}

function resolve(obj) {
  return obj && obj.__esModule ? obj.default : obj;
}

function render(loaded, props) {
  return React.createElement(resolve(loaded), props);
}

function createLoadableComponent(loadFn, options) {
  if (!options.loading) {
    throw new Error('react-loadable requires a `loading` component')
  }

  let opts = Object.assign({
    loader: null,
    loading: null,
    delay: 200,
    timeout: null,
    render: render
  }, options);

  let res = null;

  return class LoadableComponent extends React.Component {
    constructor(props) {
      super(props);

      if (!res) {
        res = loadFn(opts.loader);
      }

      this.state = {
        error: res.error,
        pastDelay: false,
        timedOut: false,
        loading: res.loading,
        loaded: res.loaded
      };
    }

    static preload() {
      if (!res) {
        res = loadFn(opts.loader);
      }
    }

    componentWillMount() {
      this._mounted = true;

      if (res.resolved) {
        return;
      }

      if (typeof opts.delay === 'number') {
        this._delay = setTimeout(() => {
          this.setState({ pastDelay: true });
        }, opts.delay);
      }

      if (typeof opts.timeout === 'number') {
        this._timeout = setTimeout(() => {
          this.setState({ timedOut: true });
        }, opts.timeout);
      }

      let update = () => {
        if (!this._mounted) {
          return;
        }

        this.setState({
          error: res.error,
          loaded: res.loaded,
          loading: res.loading
        });

        this._clearTimeouts();
      };

      res.promise.then(() => {
        update();
      }).catch(err => {
        update();
        throw err;
      });
    }

    componentWillUnmount() {
      this._mounted = false;
      this._clearTimeouts();
    }

    _clearTimeouts() {
      clearTimeout(this._delay);
      clearTimeout(this._timeout);
    }

    render() {
      if (this.state.loading || this.state.error) {
        return React.createElement(opts.loading, {
          isLoading: this.state.loading,
          pastDelay: this.state.pastDelay,
          timedOut: this.state.timedOut,
          error: this.state.error
        });
      } else if (this.state.loaded) {
        return opts.render(this.state.loaded, this.props);
      } else {
        return null;
      }
    }
  };
}

function Loadable(opts) {
  return createLoadableComponent(load, opts);
}

function LoadableMap(opts) {
  if (typeof opts.render !== 'function') {
    throw new Error('LoadableMap requires a `render(loaded, props)` function');
  }

  return createLoadableComponent(loadMap, opts);
}

Loadable.Map = LoadableMap;

module.exports = Loadable;
<commit_msg>Fix undefined `error` being set<commit_after>const React = require('react');
const isWebpackBundle = require('is-webpack-bundle');
const webpackRequireWeak = require('webpack-require-weak');
const {inspect} = require('import-inspector');

function capture(fn) {
  let reported = [];
  let stopInspecting = inspect(metadata => reported.push(metadata));
  let promise = fn();
  stopInspecting();
  return {promise, reported};
}

function load(loader) {
  let {promise, reported} = capture(() => {
    return loader();
  });

  if (reported.length > 1) {
    throw new Error('react-loadable cannot handle more than one import() in each loader');
  }

  let state = {
    loading: true,
    loaded: null,
    error: null
  };

  let metadata = reported[0] || {};

  try {
    if (isWebpackBundle) {
      if (typeof metadata.webpackRequireWeakId === 'function') {
        state.loading = false;
        state.loaded = webpackRequireWeak(metadata.webpackRequireWeakId());
      }
    } else {
      if (typeof metadata.serverSideRequirePath === 'string') {
        state.loading = false;
        state.loaded = module.require(metadata.serverSideRequirePath);
      }
    }
  } catch (err) {
    state.error = err;
  }

  state.promise = promise.then(loaded => {
    state.loading = false;
    state.loaded = loaded;
    return loaded;
  }).catch(err => {
    state.loading = false;
    state.error = err;
    throw err;
  });

  return state;
}

function loadMap(obj) {
  let state = {
    loading: false,
    loaded: {},
    error: null
  };

  let promises = [];

  try {
    Object.keys(obj).forEach(key => {
      let result = load(obj[key]);

      if (!result.loading) {
        state.loaded[key] = result.loaded;
        state.error = result.error;
      } else {
        state.loading = true;
      }

      promises.push(result.promise);

      result.promise.then(res => {
        state.loaded[key] = res;
      }).catch(err => {
        state.error = err;
      });
    });
  } catch (err) {
    state.error = err;
  }

  state.promise = Promise.all(promises).then(res => {
    state.loading = false;
    return res;
  }).catch(err => {
    state.loading = false;
    throw err;
  });

  return state;
}

function resolve(obj) {
  return obj && obj.__esModule ? obj.default : obj;
}

function render(loaded, props) {
  return React.createElement(resolve(loaded), props);
}

function createLoadableComponent(loadFn, options) {
  if (!options.loading) {
    throw new Error('react-loadable requires a `loading` component')
  }

  let opts = Object.assign({
    loader: null,
    loading: null,
    delay: 200,
    timeout: null,
    render: render
  }, options);

  let res = null;

  return class LoadableComponent extends React.Component {
    constructor(props) {
      super(props);

      if (!res) {
        res = loadFn(opts.loader);
      }

      this.state = {
        error: res.error,
        pastDelay: false,
        timedOut: false,
        loading: res.loading,
        loaded: res.loaded
      };
    }

    static preload() {
      if (!res) {
        res = loadFn(opts.loader);
      }
    }

    componentWillMount() {
      this._mounted = true;

      if (res.resolved) {
        return;
      }

      if (typeof opts.delay === 'number') {
        this._delay = setTimeout(() => {
          this.setState({ pastDelay: true });
        }, opts.delay);
      }

      if (typeof opts.timeout === 'number') {
        this._timeout = setTimeout(() => {
          this.setState({ timedOut: true });
        }, opts.timeout);
      }

      let update = () => {
        if (!this._mounted) {
          return;
        }

        this.setState({
          error: res.error,
          loaded: res.loaded,
          loading: res.loading
        });

        this._clearTimeouts();
      };

      res.promise.then(() => {
        update();
      }).catch(err => {
        update();
        throw err;
      });
    }

    componentWillUnmount() {
      this._mounted = false;
      this._clearTimeouts();
    }

    _clearTimeouts() {
      clearTimeout(this._delay);
      clearTimeout(this._timeout);
    }

    render() {
      if (this.state.loading || this.state.error) {
        return React.createElement(opts.loading, {
          isLoading: this.state.loading,
          pastDelay: this.state.pastDelay,
          timedOut: this.state.timedOut,
          error: this.state.error
        });
      } else if (this.state.loaded) {
        return opts.render(this.state.loaded, this.props);
      } else {
        return null;
      }
    }
  };
}

function Loadable(opts) {
  return createLoadableComponent(load, opts);
}

function LoadableMap(opts) {
  if (typeof opts.render !== 'function') {
    throw new Error('LoadableMap requires a `render(loaded, props)` function');
  }

  return createLoadableComponent(loadMap, opts);
}

Loadable.Map = LoadableMap;

module.exports = Loadable;
<|endoftext|>


<commit_before>Meteor.startup(function () {
  ValidateForm.addValidator('data-password', function ($el, instance) {
    var value = $el.val();
    var oldPass = $('[data-password-old]').val();

    if (value === oldPass) {
      instance._showSuccess();
      instance.log("[ValidateForm] password success", instance.el);
    } else {
      instance._showError("Passwords do not match.");
      instance.log("[ValidateForm] password failed", instance.el);
    }

    instance._validations.push(value === oldPass);
  });
});
<commit_msg>Removed Startup Function<commit_after>ValidateForm.addValidator('data-password', function ($el, instance) {
  var value = $el.val();
  var oldPass = $('[data-password-old]').val();

  if (value === oldPass) {
    instance._showSuccess();
    instance.log("[ValidateForm] password success", instance.el);
  } else {
    instance._showError("Passwords do not match.");
    instance.log("[ValidateForm] password failed", instance.el);
  }

  instance._validations.push(value === oldPass);
});<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import {camelize} from './lib/String';
import {makeCancelable} from './lib/cancelablePromise';

const mapStyles = {
  container: {
    position: 'absolute',
    width: '100%',
    height: '100%'
  },
  map: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    top: 0
  }
};

const evtNames = [
  'ready',
  'click',
  'dragend',
  'recenter',
  'bounds_changed',
  'center_changed',
  'dblclick',
  'dragstart',
  'heading_change',
  'idle',
  'maptypeid_changed',
  'mousemove',
  'mouseout',
  'mouseover',
  'projection_changed',
  'resize',
  'rightclick',
  'tilesloaded',
  'tilt_changed',
  'zoom_changed'
];

export {wrapper as GoogleApiWrapper} from './GoogleApiComponent';
export {Marker} from './components/Marker';
export {InfoWindow} from './components/InfoWindow';
export {HeatMap} from './components/HeatMap';
export {Polygon} from './components/Polygon';
export {Polyline} from './components/Polyline';
export {Circle} from './components/Circle';

export class Map extends React.Component {
  constructor(props) {
    super(props);

    if (!props.hasOwnProperty('google')) {
      throw new Error('You must include a `google` prop');
    }

    this.listeners = {};
    this.state = {
      currentLocation: {
        lat: this.props.initialCenter.lat,
        lng: this.props.initialCenter.lng
      }
    };
  }

  componentDidMount() {
    if (this.props.centerAroundCurrentLocation) {
      if (navigator && navigator.geolocation) {
        this.geoPromise = makeCancelable(
          new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(resolve, reject);
          })
        );

        this.geoPromise.promise
          .then(pos => {
            const coords = pos.coords;
            this.setState({
              currentLocation: {
                lat: coords.latitude,
                lng: coords.longitude
              }
            });
          })
          .catch(e => e);
      }
    }
    this.loadMap();
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.google !== this.props.google) {
      this.loadMap();
    }
    if (this.props.visible !== prevProps.visible) {
      this.restyleMap();
    }
    if (this.props.zoom !== prevProps.zoom) {
      this.map.setZoom(this.props.zoom);
    }
    if (this.props.center !== prevProps.center) {
      this.setState({
        currentLocation: this.props.center
      });
    }
    if (prevState.currentLocation !== this.state.currentLocation) {
      this.recenterMap();
    }
    if (this.props.bounds && this.props.bounds !== prevProps.bounds) {
      this.map.fitBounds(this.props.bounds);
    }
  }

  componentWillUnmount() {
    const {google} = this.props;
    if (this.geoPromise) {
      this.geoPromise.cancel();
    }
    Object.keys(this.listeners).forEach(e => {
      google.maps.event.removeListener(this.listeners[e]);
    });
  }

  loadMap() {
    if (this.props && this.props.google) {
      const {google} = this.props;
      const maps = google.maps;

      const mapRef = this.refs.map;
      const node = ReactDOM.findDOMNode(mapRef);
      const curr = this.state.currentLocation;
      const center = new maps.LatLng(curr.lat, curr.lng);

      const mapTypeIds = this.props.google.maps.MapTypeId || {};
      const mapTypeFromProps = String(this.props.mapType).toUpperCase();

      const mapConfig = Object.assign(
        {},
        {
          mapTypeId: mapTypeIds[mapTypeFromProps],
          center: center,
          zoom: this.props.zoom,
          maxZoom: this.props.maxZoom,
          minZoom: this.props.minZoom,
          clickableIcons: !!this.props.clickableIcons,
          disableDefaultUI: this.props.disableDefaultUI,
          zoomControl: this.props.zoomControl,
          mapTypeControl: this.props.mapTypeControl,
          scaleControl: this.props.scaleControl,
          streetViewControl: this.props.streetViewControl,
          panControl: this.props.panControl,
          rotateControl: this.props.rotateControl,
          fullscreenControl: this.props.fullscreenControl,
          scrollwheel: this.props.scrollwheel,
          draggable: this.props.draggable,
          draggableCursor: this.props.draggableCursor,
          keyboardShortcuts: this.props.keyboardShortcuts,
          disableDoubleClickZoom: this.props.disableDoubleClickZoom,
          noClear: this.props.noClear,
          styles: this.props.styles,
          gestureHandling: this.props.gestureHandling
        }
      );

      Object.keys(mapConfig).forEach(key => {
        // Allow to configure mapConfig with 'false'
        if (mapConfig[key] === null) {
          delete mapConfig[key];
        }
      });

      this.map = new maps.Map(node, mapConfig);

      evtNames.forEach(e => {
        this.listeners[e] = this.map.addListener(e, this.handleEvent(e));
      });
      maps.event.trigger(this.map, 'ready');
      this.forceUpdate();
    }
  }

  handleEvent(evtName) {
    let timeout;
    const handlerName = `on${camelize(evtName)}`;

    return e => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      timeout = setTimeout(() => {
        if (this.props[handlerName]) {
          this.props[handlerName](this.props, this.map, e);
        }
      }, 0);
    };
  }

  recenterMap() {
    const map = this.map;

    const {google} = this.props;

    if (!google) return;
    const maps = google.maps;

    if (map) {
      let center = this.state.currentLocation;
      if (!(center instanceof google.maps.LatLng)) {
        center = new google.maps.LatLng(center.lat, center.lng);
      }
      // map.panTo(center)
      map.setCenter(center);
      maps.event.trigger(map, 'recenter');
    }
  }

  restyleMap() {
    if (this.map) {
      const {google} = this.props;
      google.maps.event.trigger(this.map, 'resize');
    }
  }

  renderChildren() {
    const {children} = this.props;

    if (!children) return;

    return React.Children.map(children, c => {
      if (!c) return;
      return React.cloneElement(c, {
        map: this.map,
        google: this.props.google,
        mapCenter: this.state.currentLocation
      });
    });
  }

  render() {
    const style = Object.assign({}, mapStyles.map, this.props.style, {
      display: this.props.visible ? 'inherit' : 'none'
    });

    const containerStyles = Object.assign(
      {},
      mapStyles.container,
      this.props.containerStyle
    );

    return (

          Loading map...

        {this.renderChildren()}

    );
  }
}

Map.propTypes = {
  google: PropTypes.object,
  zoom: PropTypes.number,
  centerAroundCurrentLocation: PropTypes.bool,
  center: PropTypes.object,
  initialCenter: PropTypes.object,
  className: PropTypes.string,
  style: PropTypes.object,
  containerStyle: PropTypes.object,
  visible: PropTypes.bool,
  mapType: PropTypes.string,
  maxZoom: PropTypes.number,
  minZoom: PropTypes.number,
  clickableIcons: PropTypes.bool,
  disableDefaultUI: PropTypes.bool,
  zoomControl: PropTypes.bool,
  mapTypeControl: PropTypes.bool,
  scaleControl: PropTypes.bool,
  streetViewControl: PropTypes.bool,
  panControl: PropTypes.bool,
  rotateControl: PropTypes.bool,
  fullscreenControl: PropTypes.bool,
  scrollwheel: PropTypes.bool,
  draggable: PropTypes.bool,
  draggableCursor: PropTypes.string,
  keyboardShortcuts: PropTypes.bool,
  disableDoubleClickZoom: PropTypes.bool,
  noClear: PropTypes.bool,
  styles: PropTypes.array,
  gestureHandling: PropTypes.string,
  bounds: PropTypes.object
};

evtNames.forEach(e => (Map.propTypes[camelize(e)] = PropTypes.func));

Map.defaultProps = {
  zoom: 14,
  initialCenter: {
    lat: 37.774929,
    lng: -122.419416
  },
  center: {},
  centerAroundCurrentLocation: false,
  style: {},
  containerStyle: {},
  visible: true
};

export default Map;
<commit_msg>Update index.js<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import {camelize} from './lib/String';
import {makeCancelable} from './lib/cancelablePromise';

const mapStyles = {
  container: {
    position: 'absolute',
    width: '100%',
    height: '100%'
  },
  map: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    top: 0
  }
};

const evtNames = [
  'ready',
  'click',
  'dragend',
  'recenter',
  'bounds_changed',
  'center_changed',
  'dblclick',
  'dragstart',
  'heading_change',
  'idle',
  'maptypeid_changed',
  'mousemove',
  'mouseout',
  'mouseover',
  'projection_changed',
  'resize',
  'rightclick',
  'tilesloaded',
  'tilt_changed',
  'zoom_changed'
];

export {wrapper as GoogleApiWrapper} from './GoogleApiComponent';
export {Marker} from './components/Marker';
export {InfoWindow} from './components/InfoWindow';
export {HeatMap} from './components/HeatMap';
export {Polygon} from './components/Polygon';
export {Polyline} from './components/Polyline';
export {Circle} from './components/Circle';

export class Map extends React.Component {
  constructor(props) {
    super(props);

    if (!props.hasOwnProperty('google')) {
      throw new Error('You must include a `google` prop');
    }

    this.listeners = {};
    this.state = {
      currentLocation: {
        lat: this.props.initialCenter.lat,
        lng: this.props.initialCenter.lng
      }
    };
  }

  componentDidMount() {
    if (this.props.centerAroundCurrentLocation) {
      if (navigator && navigator.geolocation) {
        this.geoPromise = makeCancelable(
          new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(resolve, reject);
          })
        );

        this.geoPromise.promise
          .then(pos => {
            const coords = pos.coords;
            this.setState({
              currentLocation: {
                lat: coords.latitude,
                lng: coords.longitude
              }
            });
          })
          .catch(e => e);
      }
    }
    this.loadMap();
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.google !== this.props.google) {
      this.loadMap();
    }
    if (this.props.visible !== prevProps.visible) {
      this.restyleMap();
    }
    if (this.props.zoom !== prevProps.zoom) {
      this.map.setZoom(this.props.zoom);
    }
    if (this.props.center !== prevProps.center) {
      this.setState({
        currentLocation: this.props.center
      });
    }
    if (prevState.currentLocation !== this.state.currentLocation) {
      this.recenterMap();
    }
    if (this.props.bounds && this.props.bounds !== prevProps.bounds) {
      this.map.fitBounds(this.props.bounds);
    }
  }

  componentWillUnmount() {
    const {google} = this.props;
    if (this.geoPromise) {
      this.geoPromise.cancel();
    }
    Object.keys(this.listeners).forEach(e => {
      google.maps.event.removeListener(this.listeners[e]);
    });
  }

  loadMap() {
    if (this.props && this.props.google) {
      const {google} = this.props;
      const maps = google.maps;

      const mapRef = this.refs.map;
      const node = ReactDOM.findDOMNode(mapRef);
      const curr = this.state.currentLocation;
      const center = new maps.LatLng(curr.lat, curr.lng);

      const mapTypeIds = this.props.google.maps.MapTypeId || {};
      const mapTypeFromProps = String(this.props.mapType).toUpperCase();

      const mapConfig = Object.assign(
        {},
        {
          mapTypeId: mapTypeIds[mapTypeFromProps],
          center: center,
          zoom: this.props.zoom,
          maxZoom: this.props.maxZoom,
          minZoom: this.props.minZoom,
          clickableIcons: !!this.props.clickableIcons,
          disableDefaultUI: this.props.disableDefaultUI,
          zoomControl: this.props.zoomControl,
          zoomControlOptions: this.props.zoomControlOptions,
          mapTypeControl: this.props.mapTypeControl,
          mapTypeControlOptions: this.props.mapTypeControlOptions,
          scaleControl: this.props.scaleControl,
          streetViewControl: this.props.streetViewControl,
          streetViewControlOptions: this.props.streetViewControlOptions,
          panControl: this.props.panControl,
          rotateControl: this.props.rotateControl,
          fullscreenControl: this.props.fullscreenControl,
          scrollwheel: this.props.scrollwheel,
          draggable: this.props.draggable,
          draggableCursor: this.props.draggableCursor,
          keyboardShortcuts: this.props.keyboardShortcuts,
          disableDoubleClickZoom: this.props.disableDoubleClickZoom,
          noClear: this.props.noClear,
          styles: this.props.styles,
          gestureHandling: this.props.gestureHandling
        }
      );

      Object.keys(mapConfig).forEach(key => {
        // Allow to configure mapConfig with 'false'
        if (mapConfig[key] === null) {
          delete mapConfig[key];
        }
      });

      this.map = new maps.Map(node, mapConfig);

      evtNames.forEach(e => {
        this.listeners[e] = this.map.addListener(e, this.handleEvent(e));
      });
      maps.event.trigger(this.map, 'ready');
      this.forceUpdate();
    }
  }

  handleEvent(evtName) {
    let timeout;
    const handlerName = `on${camelize(evtName)}`;

    return e => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      timeout = setTimeout(() => {
        if (this.props[handlerName]) {
          this.props[handlerName](this.props, this.map, e);
        }
      }, 0);
    };
  }

  recenterMap() {
    const map = this.map;

    const {google} = this.props;

    if (!google) return;
    const maps = google.maps;

    if (map) {
      let center = this.state.currentLocation;
      if (!(center instanceof google.maps.LatLng)) {
        center = new google.maps.LatLng(center.lat, center.lng);
      }
      // map.panTo(center)
      map.setCenter(center);
      maps.event.trigger(map, 'recenter');
    }
  }

  restyleMap() {
    if (this.map) {
      const {google} = this.props;
      google.maps.event.trigger(this.map, 'resize');
    }
  }

  renderChildren() {
    const {children} = this.props;

    if (!children) return;

    return React.Children.map(children, c => {
      if (!c) return;
      return React.cloneElement(c, {
        map: this.map,
        google: this.props.google,
        mapCenter: this.state.currentLocation
      });
    });
  }

  render() {
    const style = Object.assign({}, mapStyles.map, this.props.style, {
      display: this.props.visible ? 'inherit' : 'none'
    });

    const containerStyles = Object.assign(
      {},
      mapStyles.container,
      this.props.containerStyle
    );

    return (

          Loading map...

        {this.renderChildren()}

    );
  }
}

Map.propTypes = {
  google: PropTypes.object,
  zoom: PropTypes.number,
  centerAroundCurrentLocation: PropTypes.bool,
  center: PropTypes.object,
  initialCenter: PropTypes.object,
  className: PropTypes.string,
  style: PropTypes.object,
  containerStyle: PropTypes.object,
  visible: PropTypes.bool,
  mapType: PropTypes.string,
  maxZoom: PropTypes.number,
  minZoom: PropTypes.number,
  clickableIcons: PropTypes.bool,
  disableDefaultUI: PropTypes.bool,
  zoomControl: PropTypes.bool,
  zoomControlOptions: PropTypes.object,
  mapTypeControl: PropTypes.bool,
  mapTypeControlOptions: PropTypes.bool,
  scaleControl: PropTypes.bool,
  streetViewControl: PropTypes.bool,
  streetViewControlOptions: PropTypes.object,
  panControl: PropTypes.bool,
  rotateControl: PropTypes.bool,
  fullscreenControl: PropTypes.bool,
  scrollwheel: PropTypes.bool,
  draggable: PropTypes.bool,
  draggableCursor: PropTypes.string,
  keyboardShortcuts: PropTypes.bool,
  disableDoubleClickZoom: PropTypes.bool,
  noClear: PropTypes.bool,
  styles: PropTypes.array,
  gestureHandling: PropTypes.string,
  bounds: PropTypes.object
};

evtNames.forEach(e => (Map.propTypes[camelize(e)] = PropTypes.func));

Map.defaultProps = {
  zoom: 14,
  initialCenter: {
    lat: 37.774929,
    lng: -122.419416
  },
  center: {},
  centerAroundCurrentLocation: false,
  style: {},
  containerStyle: {},
  visible: true
};

export default Map;
<|endoftext|>