<commit_before>define([
    'streamhub-sdk/jquery',
    'streamhub-sdk/content/views/content-list-view',
    'streamhub-sdk/content/views/content-view',
    'text!streamhub-wall/style.css',
    'inherits'
], function($, ContentListView, ContentView, MEDIA_WALL_CSS, inherits) {
    'use strict';

    var MEDIA_WALL_STYLE_EL;

    /**
     * A view that displays Content in a media wall.
     * @param opts {Object} A set of options to config the view with
     * @param opts.el {HTMLElement} The element in which to render the streamed content
     * @param opts.relayoutWait {number} The number of milliseconds to wait when debouncing
     *        .relayout(). Defaults to 200ms.
     * @param opts.css {boolean} Whether to insert default media wall css. Default true.
     * @constructor
     */
    var MediaWallView = function(opts) {
        var self = this;
        opts = opts || {};

        this._id = new Date().getTime();
        this._autoFitColumns = true;
        this._contentWidth = opts.minContentWidth || 300;
        this._columnViews = [];
        this._columnInsertIndex = 0;
        this._containerInnerWidth = 0;

        this.debouncedFitColumns = debounce(function () {
            self._fitColumns();
        }, opts.debounceRelayout || 200);

        ContentListView.call(this, opts);

        $(window).resize(function(e) {
            if (self._autoFitColumns) {
                self.fitColumns();
            }
        });

        opts.css = (typeof opts.css === 'undefined') ? true : opts.css;
        if (!MEDIA_WALL_STYLE_EL && opts.css) {
            MEDIA_WALL_STYLE_EL = $('<style>'+MEDIA_WALL_CSS+'</style>').prependTo('head');
        }
        if (opts.columns && typeof opts.columns === 'number') {
            this._autoFitColumns = false;
            this.setColumns(opts.columns);
        }
        if (this._autoFitColumns) {
            this.fitColumns({ force: true });
        }
    };
    inherits(MediaWallView, ContentListView);

    MediaWallView.prototype.mediaWallClassName = 'streamhub-media-wall-view';
    MediaWallView.prototype.columnClassName = 'hub-wall-column';

    /**
     * Gets the style element associated with this instance of MediaWallView
     * @returns {HTMLElement} The style element for this MediaWallView
     */
    MediaWallView.prototype._getWallStyleEl = function () {
        var $wallStyleEl = $('#wall-style-' + this._id);
        if ($wallStyleEl) {
            return $wallStyleEl;
        }
    };

    /**
     * Sets the column width in the style element for this MediaWallView
     * instance.
     * @returns {Number} The width of the column in pixels
     */
    MediaWallView.prototype._setColumnWidth = function (width) {
        var $wallStyleEl = this._getWallStyleEl();
        if ($wallStyleEl) {
            $wallStyleEl.remove();
        }
        var wallCss = '.streamhub-media-wall-'+this._id+' .hub-wall-column { width: ' + width + '; }';
        $wallStyleEl = $('<style id="wall-style-' + this._id + '">'+wallCss+'</style>');
        $wallStyleEl.appendTo('head');
        return this._getColumnWidth();
    };

    /**
     * Gets the column width
     * @returns {Number} The width of the column in pixels
     */
    MediaWallView.prototype._getColumnWidth = function () {
        var $contentContainerEl = this.$el.find('.'+this.columnClassName);
        if ($contentContainerEl.length) {
            this._columnWidth = $contentContainerEl[0].getBoundingClientRect().width;
            return this._columnWidth;
        }
        return 0;
    };

    /**
     * Set the element that this ContentListView renders in
     * @param element {HTMLElement} The element to render the ContentListView in
     */
    MediaWallView.prototype.setElement = function (el) {
        ContentListView.prototype.setElement.call(this, el);
        this.$el
            .addClass(this.mediaWallClassName)
            .addClass('streamhub-media-wall-' + this._id);

        this.fitColumns();
    };

    MediaWallView.prototype.fitColumns = function (opts) {
        if (this._containerInnerWidth === this.$el.innerWidth()) {
            return;
        }
        opts = opts || {};

        if (opts.force) {
            this._fitColumns.apply(this, arguments);
        } else {
            this.debouncedFitColumns.apply(this, arguments);
        }
    };

    /**
     * Determines the number columns based on the configured #_contentWidth.
     * Initiates relayout logic for the determined number of columns.
     * @param opts {Object}
     */
    MediaWallView.prototype._fitColumns = function (opts) {
        var latestWidth = this.$el.innerWidth();
        // If width hasn't changed, do nothing
        if (latestWidth === this._containerInnerWidth) {
            return;
        }

        this._containerInnerWidth = latestWidth;
        var numColumns = parseInt(this._containerInnerWidth / this._contentWidth, 10) || 1;
        this._clearColumns();
        this.setColumns(numColumns);
    };

    /**
     * Creates a column view for the number of columns specified. Triggers
     * relayout.
     * @param numColumns {Number} The number of columns the MediaWallView should be composed of
     */
    MediaWallView.prototype.setColumns = function (numColumns) {
        this._numberOfColumns = numColumns;
        var $wallStyleEl = this._getWallStyleEl();
        if ($wallStyleEl) {
            $wallStyleEl.remove();
        }
        $wallStyleEl = $('<style id="wall-style-' + this._id + '"></style');
        this._setColumnWidth((100/this._numberOfColumns) + '%');

        for (var i=0; i < this._numberOfColumns; i++) {
            this._createColumnView();
        }

        this._moreAmount = this._moreAmount || numColumns * 2; // Show more displays 2 new rows

        this.relayout();
    };

    /**
     * Gets the number of maximum visible items for a given column view
     * @returns {Number} The number of maximum visible items for a given column view
     */
    MediaWallView.prototype._getMaxVisibleItemsForColumn = function () {
        return this._maxVisibleItems/this._numberOfColumns;
    };

    /**
     * Creates a column view and appends it into the DOM
     * @returns {View} The view representing a column in the MediaWall. Often a type of ListView.
     */
    MediaWallView.prototype._createColumnView = function () {
        var columnView = new ContentListView({
            maxVisibleItems: this._getMaxVisibleItemsForColumn(),
            stash: this.more
        });
        this._columnViews.push(columnView);
        columnView.$el.addClass(this.columnClassName);
        this.$listEl.append(columnView.$el);
        return columnView;
    };

    /**
     * Removes column views from the MediaWallView
     */
    MediaWallView.prototype._clearColumns = function () {
        for (var i=0; i < this._columnViews.length; i++) {
            var columnView = this._columnViews[i];
            columnView.detach();
            columnView.destroy();
        }
        this._columnViews = [];
    };

    /**
     * Insert a contentView into the Media Wall's column ContentListViews
     * @protected
     * @param view {View} The view to add to this.el
     * @param [forcedIndex] {number} Index of the view in this.views
     */
    MediaWallView.prototype._insert = function (contentView, forcedIndex) {
        var targetColumnView = this._columnViews[this._columnInsertIndex];
        this._columnInsertIndex++;
        this._columnInsertIndex = this._columnInsertIndex == this._columnViews.length ? 0 : this._columnInsertIndex;

        if (typeof(forcedIndex) === 'number') {
            forcedIndex = Math.min(
                    Math.ceil(forcedIndex / this._columnViews.length),
                    targetColumnView.views.length);
        }
        targetColumnView.add(contentView, forcedIndex);

        // IE8 will not automatically push the 'show more' button down as the
        // wall grows. Adding and removing a random class will force a repaint
        var randomClass = String(Math.floor(Math.random()));
        this.$el.addClass(randomClass);
        this.$el.removeClass(randomClass);
    };

    MediaWallView.prototype.relayout = function (opts) {
        opts = opts || {};
        this.columnBasedLayout();
    };

    /**
     * The column-based round-robin strategy of laying out content views
     */
    MediaWallView.prototype.columnBasedLayout = function () {
        // Round-robin through columns, inserting each column with the next
        // available view
        this._columnInsertIndex = 0;
        for (var i=0; i < this.views.length; i++) {
            var contentView = this.views[i];
            var index = this._isIndexedView(contentView) ? i : undefined;
            if (contentView) {
                this._insert(contentView.content, index);
            }
        }
    };

    /**
     * Show More content.
     * ContentListView keeps track of an internal ._newContentGoal
     *     which is how many more items he wishes he had.
     *     This increases that goal and marks the Writable
     *     side of ContentListView as ready for more writes.
     * @param numToShow {number} The number of items to try to add
     */
    MediaWallView.prototype.showMore = function (numToShow) {
        // When fetching more content from the archive, remove the bounded
        // visible limit
        for (var i=0; i < this._columnViews.length; i++) {
            this._columnViews[i].bounded(false);
        }
        ContentListView.prototype.showMore.call(this, numToShow);
    };

    /**
     * Returns a function, that, as long as it continues to be invoked, will not be triggered.
     * The function will be called after it stops being called for N milliseconds.
     * Copied from Underscore.js (MIT License) http://underscorejs.org/docs/underscore.html#section-65
     * @param func {function} The function to debounce
     * @param wait {number} The number of milliseconds to wait for execution of func
     * @param immediate {boolean} trigger the function on the leading edge, instead of the trailing.
     * @return {function} A debounced version of the passed `func`
     */
    function debounce(func, wait, immediate) {
        var timeout, result;
        return function() {
            var context = this,
                args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) {
                    result = func.apply(context, args);
                }
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
                result = func.apply(context, args);
            }
            return result;
        };
    }

    MediaWallView.prototype.destroy = function () {
        this._clearColumns();
        this._columnViews = null;
        ContentListView.prototype.destroy.call(this);
    };

    return MediaWallView;
});
<commit_msg>Configurable strategy for determining column of insertion.<commit_after>define([
    'streamhub-sdk/jquery',
    'streamhub-sdk/content/views/content-list-view',
    'streamhub-sdk/content/views/content-view',
    'text!streamhub-wall/style.css',
    'inherits'
], function($, ContentListView, ContentView, MEDIA_WALL_CSS, inherits) {
    'use strict';

    var MEDIA_WALL_STYLE_EL;

    /**
     * A view that displays Content in a media wall.
     * @param opts {Object} A set of options to config the view with
     * @param opts.el {HTMLElement} The element in which to render the streamed content
     * @param opts.relayoutWait {number} The number of milliseconds to wait when debouncing
     *        .relayout(). Defaults to 200ms.
     * @param opts.css {boolean} Whether to insert default media wall css. Default true.
     * @constructor
     */
    var MediaWallView = function(opts) {
        var self = this;
        opts = opts || {};

        this._id = new Date().getTime();
        this._autoFitColumns = true;
        this._contentWidth = opts.minContentWidth || 300;
        this._columnViews = [];
        this._columnInsertIndex = 0;
        this._containerInnerWidth = 0;

        this._insertStrategy = opts.insertStrategy || MediaWallView.INSERT_STRATEGIES.SHORTEST_COLUMN;

        this.debouncedFitColumns = debounce(function () {
            self._fitColumns();
        }, opts.debounceRelayout || 200);

        ContentListView.call(this, opts);

        $(window).resize(function(e) {
            if (self._autoFitColumns) {
                self.fitColumns();
            }
        });

        opts.css = (typeof opts.css === 'undefined') ? true : opts.css;
        if (!MEDIA_WALL_STYLE_EL && opts.css) {
            MEDIA_WALL_STYLE_EL = $('<style>'+MEDIA_WALL_CSS+'</style>').prependTo('head');
        }
        if (opts.columns && typeof opts.columns === 'number') {
            this._autoFitColumns = false;
            this.setColumns(opts.columns);
        }
        if (this._autoFitColumns) {
            this.fitColumns({ force: true });
        }
    };
    inherits(MediaWallView, ContentListView);

    MediaWallView.prototype.mediaWallClassName = 'streamhub-media-wall-view';
    MediaWallView.prototype.columnClassName = 'hub-wall-column';

    MediaWallView.INSERT_STRATEGIES = {
        ROUND_ROBIN: function () {
            this._columnInsertIndex++;
            this._columnInsertIndex = this._columnInsertIndex == this._columnViews.length ? 0 : this._columnInsertIndex;
            return this._columnViews[this._columnInsertIndex];
        },
        SHORTEST_COLUMN: function () {
            var targetColIndex = this._columnInsertIndex;
            var shortestHeight;
            for (var i=0; i < this._columnViews.length; i++) {
                var colHeight = this._columnViews[i].$el.height();
                if (shortestHeight === undefined) {
                    shortestHeight = colHeight;
                    targetColIndex = i;
                    continue;
                }
                if (colHeight < shortestHeight) {
                    shortestHeight = colHeight;
                    targetColIndex = i;
                }
            }
            return this._columnViews[targetColIndex];
        }
    };

    /**
     * Gets the style element associated with this instance of MediaWallView
     * @returns {HTMLElement} The style element for this MediaWallView
     */
    MediaWallView.prototype._getWallStyleEl = function () {
        var $wallStyleEl = $('#wall-style-' + this._id);
        if ($wallStyleEl) {
            return $wallStyleEl;
        }
    };

    /**
     * Sets the column width in the style element for this MediaWallView
     * instance.
     * @returns {Number} The width of the column in pixels
     */
    MediaWallView.prototype._setColumnWidth = function (width) {
        var $wallStyleEl = this._getWallStyleEl();
        if ($wallStyleEl) {
            $wallStyleEl.remove();
        }
        var wallCss = '.streamhub-media-wall-'+this._id+' .hub-wall-column { width: ' + width + '; }';
        $wallStyleEl = $('<style id="wall-style-' + this._id + '">'+wallCss+'</style>');
        $wallStyleEl.appendTo('head');
        return this._getColumnWidth();
    };

    /**
     * Gets the column width
     * @returns {Number} The width of the column in pixels
     */
    MediaWallView.prototype._getColumnWidth = function () {
        var $contentContainerEl = this.$el.find('.'+this.columnClassName);
        if ($contentContainerEl.length) {
            this._columnWidth = $contentContainerEl[0].getBoundingClientRect().width;
            return this._columnWidth;
        }
        return 0;
    };

    /**
     * Set the element that this ContentListView renders in
     * @param element {HTMLElement} The element to render the ContentListView in
     */
    MediaWallView.prototype.setElement = function (el) {
        ContentListView.prototype.setElement.call(this, el);
        this.$el
            .addClass(this.mediaWallClassName)
            .addClass('streamhub-media-wall-' + this._id);

        this.fitColumns();
    };

    MediaWallView.prototype.fitColumns = function (opts) {
        if (this._containerInnerWidth === this.$el.innerWidth()) {
            return;
        }
        opts = opts || {};

        if (opts.force) {
            this._fitColumns.apply(this, arguments);
        } else {
            this.debouncedFitColumns.apply(this, arguments);
        }
    };

    /**
     * Determines the number columns based on the configured #_contentWidth.
     * Initiates relayout logic for the determined number of columns.
     * @param opts {Object}
     */
    MediaWallView.prototype._fitColumns = function (opts) {
        var latestWidth = this.$el.innerWidth();
        // If width hasn't changed, do nothing
        if (latestWidth === this._containerInnerWidth) {
            return;
        }

        this._containerInnerWidth = latestWidth;
        var numColumns = parseInt(this._containerInnerWidth / this._contentWidth, 10) || 1;
        this._clearColumns();
        this.setColumns(numColumns);
    };

    /**
     * Creates a column view for the number of columns specified. Triggers
     * relayout.
     * @param numColumns {Number} The number of columns the MediaWallView should be composed of
     */
    MediaWallView.prototype.setColumns = function (numColumns) {
        this._numberOfColumns = numColumns;
        var $wallStyleEl = this._getWallStyleEl();
        if ($wallStyleEl) {
            $wallStyleEl.remove();
        }
        $wallStyleEl = $('<style id="wall-style-' + this._id + '"></style');
        this._setColumnWidth((100/this._numberOfColumns) + '%');

        for (var i=0; i < this._numberOfColumns; i++) {
            this._createColumnView();
        }

        this._moreAmount = this._moreAmount || numColumns * 2; // Show more displays 2 new rows

        this.relayout();
    };

    /**
     * Gets the number of maximum visible items for a given column view
     * @returns {Number} The number of maximum visible items for a given column view
     */
    MediaWallView.prototype._getMaxVisibleItemsForColumn = function () {
        return this._maxVisibleItems/this._numberOfColumns;
    };

    /**
     * Creates a column view and appends it into the DOM
     * @returns {View} The view representing a column in the MediaWall. Often a type of ListView.
     */
    MediaWallView.prototype._createColumnView = function () {
        var columnView = new ContentListView({
            maxVisibleItems: this._getMaxVisibleItemsForColumn(),
            stash: this.more
        });
        this._columnViews.push(columnView);
        columnView.$el.addClass(this.columnClassName);
        this.$listEl.append(columnView.$el);
        return columnView;
    };

    /**
     * Removes column views from the MediaWallView
     */
    MediaWallView.prototype._clearColumns = function () {
        for (var i=0; i < this._columnViews.length; i++) {
            var columnView = this._columnViews[i];
            columnView.detach();
            columnView.destroy();
        }
        this._columnViews = [];
    };

    /**
     * Insert a contentView into the Media Wall's column ContentListViews
     * @protected
     * @param view {View} The view to add to this.el
     * @param [forcedIndex] {number} Index of the view in this.views
     */
    MediaWallView.prototype._insert = function (contentView, forcedIndex) {
        var targetColumnView = this._insertStrategy(contentView);

        if (typeof(forcedIndex) === 'number') {
            forcedIndex = Math.min(
                    Math.ceil(forcedIndex / this._columnViews.length),
                    targetColumnView.views.length);
        }
        targetColumnView.add(contentView, forcedIndex);

        // IE8 will not automatically push the 'show more' button down as the
        // wall grows. Adding and removing a random class will force a repaint
        var randomClass = String(Math.floor(Math.random()));
        this.$el.addClass(randomClass);
        this.$el.removeClass(randomClass);
    };

    MediaWallView.prototype.relayout = function (opts) {
        opts = opts || {};

        // Re-insert all content views
        this._columnInsertIndex = 0;
        for (var i=0; i < this.views.length; i++) {
            var contentView = this.views[i];
            var index = this._isIndexedView(contentView) ? i : undefined;
            if (contentView) {
                this._insert(contentView.content, index);
            }
        }
    };

    /**
     * Show More content.
     * ContentListView keeps track of an internal ._newContentGoal
     *     which is how many more items he wishes he had.
     *     This increases that goal and marks the Writable
     *     side of ContentListView as ready for more writes.
     * @param numToShow {number} The number of items to try to add
     */
    MediaWallView.prototype.showMore = function (numToShow) {
        // When fetching more content from the archive, remove the bounded
        // visible limit
        for (var i=0; i < this._columnViews.length; i++) {
            this._columnViews[i].bounded(false);
        }
        ContentListView.prototype.showMore.call(this, numToShow);
    };

    /**
     * Returns a function, that, as long as it continues to be invoked, will not be triggered.
     * The function will be called after it stops being called for N milliseconds.
     * Copied from Underscore.js (MIT License) http://underscorejs.org/docs/underscore.html#section-65
     * @param func {function} The function to debounce
     * @param wait {number} The number of milliseconds to wait for execution of func
     * @param immediate {boolean} trigger the function on the leading edge, instead of the trailing.
     * @return {function} A debounced version of the passed `func`
     */
    function debounce(func, wait, immediate) {
        var timeout, result;
        return function() {
            var context = this,
                args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) {
                    result = func.apply(context, args);
                }
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
                result = func.apply(context, args);
            }
            return result;
        };
    }

    MediaWallView.prototype.destroy = function () {
        this._clearColumns();
        this._columnViews = null;
        ContentListView.prototype.destroy.call(this);
    };

    return MediaWallView;
});
<|endoftext|>


<commit_before>(function ( $ ) {
    $.fn.pOn = function (events, priority, callback) {

        var pEvents = this.data("pEvents") || [];

        pEvents.push([
            priority,
            callback
        ]);

        pEvents.sort(function (e1, e2) {
            return e1[0] - e2[0];
        });

        this.data("pEvents", pEvents);

        if (pEvents.length > 1) { return; }

        this.on(events, selector, function () {
            var pEvs = $(this).data("pEvents") || [];
            for (var i = 0; i < pEvs.length; ++i) {
                pEvs[i][1].call(this);
            }
        });
    }
})($);
<commit_msg>Removed selctor parameter<commit_after>(function ( $ ) {
    $.fn.pOn = function (events, priority, callback) {

        var pEvents = this.data("pEvents") || [];

        pEvents.push([
            priority,
            callback
        ]);

        pEvents.sort(function (e1, e2) {
            return e1[0] - e2[0];
        });

        this.data("pEvents", pEvents);

        if (pEvents.length > 1) { return; }

        this.on(events, function () {
            var pEvs = $(this).data("pEvents") || [];
            for (var i = 0; i < pEvs.length; ++i) {
                pEvs[i][1].call(this);
            }
        });
    }
})($);
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import RaisedButton from 'material-ui/RaisedButton';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import FlatButton from 'material-ui/FlatButton';
import keycode from 'keycode';
import ActivityArea from './ActivityArea';
import CommitTree from './CommitTreePanel';
import StagingArea from './StagingAreaPanel';
import {Tabs, Tab} from 'material-ui/Tabs';

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
import injectTapEventPlugin from 'react-tap-event-plugin';

import Git from 'nodegit';

// var pathToRepo = require('path').resolve('../js-reporters');

const getCommitsFromRepo = function(repo) {

  let pathToRepo = require('path').resolve(repo);
  Git.Repository.open(pathToRepo)
  .then(function(repo) {
    return repo.getMasterCommit();
  })
  .then(function( firstMasterCommit ) {
    let history = firstMasterCommit.history( Git.Revwalk.SORT.Time);
    history.on("end", walk);
    history.start();
  })
  .done();

  //   function passed to history.on() listener to receive commits' info.
  //   calls the setCommitState of App class to set new state
  const walk = (commitsArr) => {
    let commits = [];
      commitsArr.forEach( function(commit) {
        commits.push({
          sha: commit.sha(),
          author: commit.author().name(),
          email: commit.author().email(),
          date: commit.date().toString(),
          message: commit.message()
        });
      });

      const newRepo = {
        repoName:repo.slice(3),
        commits: commits
      };

      this.returnRepo(newRepo);
  };

}

const darkMuiTheme = getMuiTheme(darkBaseTheme);

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.state={ value:props.pathToRepo };
  }

  updateValue = (event) => {
    this.setState({
      value: event.target.value
    });
  }

  sendQuery = (event) => {
    if(!event.which || (event.which && event.which === 13) )
      this.props.onKeyPress(this.state.value);
  }

  render() {
    const style = {
      margin:10
    };

    return (

        <input type="text" placeholder="Enter Repo name here..." ref="textField"
        value={this.state.value} onChange={this.updateValue} onKeyDown={this.sendQuery} />
        <RaisedButton label="Get Commits!"  onMouseDown={this.sendQuery} />

    )
  }
}

class RepoTable extends React.Component {

  constructor(props) {
    super(props);
  }

  handleClick = (i) => {
    this.props.selectRepo(i);
  }

  render() {
    const style= {
      margin: 5,
    };

    let rows = [];
    this.props.repos.forEach((function(repo, index) {
        rows.push(
          <Card style={style} key={index} onMouseDown={this.handleClick.bind(this, index)} >
            <CardHeader title={repo.repoName} />
          </Card>
        );
    }).bind(this));
    return (

{rows}

    )
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pathToRepo:'' ,
      currentRepo: '',
      currentRepoCommits: [],
      repos: [],
      repoNames: [],
      tabValue: 'CommitTree'
    };
  }

  handleTabChange = (value) => {
    this.setState({
      tabValue: value
    });
  }

  handleKeyPressChange = (passedPath) => {
    let repoName = passedPath.slice(3);
    if(this.state.repoNames.indexOf(repoName) == -1) {
      //call to global function
      (getCommitsFromRepo.bind(this))(passedPath);
    }
    else {

    }
  }

  setCurrentCommits = (repo) => {
    this.setState({
      currentRepo: repo.repoName,
      currentRepoCommits: repo.commits
    });
  }

  handleRepoClick = (index) => {
    this.setCurrentCommits(this.state.repos[index]);
  }

  returnRepo = (newRepo) =>
  {
    let repos = this.state.repos;
    let repoNames = this.state.repoNames;
    repos.push(newRepo);
    repoNames.push(newRepo.repoName);
    this.setState({
      repos: repos,
      repoNames: repoNames
    });
    this.setCurrentCommits(newRepo);
  }

  componentWillMount = () => {
    injectTapEventPlugin();
  }

  render() {

    const styles = {
      mainPanel: {
        display: 'flex',
        border: '1px solid black',
        width: '80%',
        height:400
      },
      repos: {
        flexShrink:3,
        width: '100%'
      },
      tabs: {
        border:'1px solid black',
        overflow: 'auto',
        width: '100%'
      }
    };

    return (
      <MuiThemeProvider muiTheme={darkMuiTheme}>

          <SearchBar pathToRepo={this.state.pathToRepo} onKeyPress={this.handleKeyPressChange} />

            <RepoTable style={styles.repos} repos={this.state.repos} selectRepo={this.handleRepoClick} />

            <Tabs style={styles.tabs} value={this.state.tabValue}  onChange={this.handleTabChange} >

              <Tab label="Commits" value="CommitTree" >
                <CommitTree commits={this.state.currentRepoCommits}  />
              </Tab>

              <Tab label="Staging Area" value="StagingArea" >
                <StagingArea repo={this.state.currentRepo} />
              </Tab>

            </Tabs>

      </MuiThemeProvider>
    )
  }

}

ReactDOM.render(
  <App  />,
  document.getElementById('app')
);
<commit_msg>Misc: small changes in src/main.js file<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import RaisedButton from 'material-ui/RaisedButton';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import FlatButton from 'material-ui/FlatButton';
import keycode from 'keycode';
import ActivityArea from './ActivityArea';
import CommitTree from './CommitTreePanel';
import StagingArea from './StagingAreaPanel';
import {Tabs, Tab} from 'material-ui/Tabs';

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
import injectTapEventPlugin from 'react-tap-event-plugin';

import Git from 'nodegit';

// var pathToRepo = require('path').resolve('../js-reporters');

const getCommitsFromRepo = function(repo) {

  let pathToRepo = require('path').resolve(repo);
  Git.Repository.open(pathToRepo)
  .then(function(repo) {
    return repo.getMasterCommit();
  })
  .then(function( firstMasterCommit ) {
    let history = firstMasterCommit.history( Git.Revwalk.SORT.Time);
    history.on("end", walk);
    history.start();
  })
  .done();

  //   function passed to history.on() listener to receive commits' info.
  //   calls the setCommitState of App class to set new state
  const walk = (commitsArr) => {
    let commits = [];
      commitsArr.forEach( function(commit) {
        commits.push({
          sha: commit.sha(),
          author: commit.author().name(),
          email: commit.author().email(),
          date: commit.date().toString(),
          message: commit.message()
        });
      });

      const newRepo = {
        repoName:repo.slice(3),
        commits: commits
      };

      this.returnRepo(newRepo);
  };

}

const darkMuiTheme = getMuiTheme(darkBaseTheme);

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.state={ value:props.pathToRepo };
  }

  updateValue = (event) => {
    this.setState({
      value: event.target.value
    });
  }

  sendQuery = (event) => {
    if(!event.which || (event.which && event.which === 13) )
      this.props.onKeyPress(this.state.value);
  }

  render() {
    const style = {
      margin:10
    };

    return (

        <input type="text" placeholder="Enter Repo name here..." ref="textField"
        value={this.state.value} onChange={this.updateValue} onKeyDown={this.sendQuery} />
        <RaisedButton label="Get Commits!"  onMouseDown={this.sendQuery} />

    )
  }
}

class RepoTable extends React.Component {

  constructor(props) {
    super(props);
  }

  handleClick = (i) => {
    this.props.selectRepo(i);
  }

  render() {
    const style= {
      margin: 5,
      cursor: 'pointer'
    };

    let rows = [];
    this.props.repos.forEach((function(repo, index) {
        rows.push(
          <Card style={style} key={index} onMouseDown={this.handleClick.bind(this, index)} >
            <CardHeader title={repo.repoName} />
          </Card>
        );
    }).bind(this));
    return (

{rows}

    )
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pathToRepo:'' ,
      currentRepo: '',
      currentRepoCommits: [],
      repos: [],
      repoNames: [],
      tabValue: 'CommitTree'
    };
  }

  handleTabChange = (value) => {
    this.setState({
      tabValue: value
    });
  }

  handleKeyPressChange = (passedPath) => {
    let repoName = passedPath.slice(3);
    if(this.state.repoNames.indexOf(repoName) == -1) {
      //call to global function
      (getCommitsFromRepo.bind(this))(passedPath);
    }
    else {

    }
  }

  setCurrentCommits = (repo) => {
    this.setState({
      currentRepo: repo.repoName,
      currentRepoCommits: repo.commits
    });
  }

  handleRepoClick = (index) => {
    this.setCurrentCommits(this.state.repos[index]);
  }

  returnRepo = (newRepo) =>
  {
    let repos = this.state.repos;
    let repoNames = this.state.repoNames;
    repos.push(newRepo);
    repoNames.push(newRepo.repoName);
    this.setState({
      repos: repos,
      repoNames: repoNames
    });
    this.setCurrentCommits(newRepo);
  }

  componentWillMount = () => {
    injectTapEventPlugin();
  }

  //for dev prurposes only
  componentDidMount = () => {
    this.handleKeyPressChange('../git-gui');
  }

  render() {

    const styles = {
      mainPanel: {
        display: 'flex',
        border: '1px solid black',
        width: '80%',
        height:400
      },
      repos: {
        flexShrink:3,
        width: '100%'
      },
      tabs: {
        border:'1px solid black',
        overflow: 'auto',
        width: '100%'
      }
    };

    return (
      <MuiThemeProvider muiTheme={getMuiTheme()}>

          <SearchBar pathToRepo={this.state.pathToRepo} onKeyPress={this.handleKeyPressChange} />

            <RepoTable style={styles.repos} repos={this.state.repos} selectRepo={this.handleRepoClick} />

            <Tabs style={styles.tabs} value={this.state.tabValue}  onChange={this.handleTabChange} >

              <Tab label="Commits" value="CommitTree" >
                <CommitTree commits={this.state.currentRepoCommits}  />
              </Tab>

              <Tab label="Staging Area" value="StagingArea" >
                <StagingArea repo={this.state.currentRepo} />
              </Tab>

            </Tabs>

      </MuiThemeProvider>
    )
  }

}

ReactDOM.render(
  <App  />,
  document.getElementById('app')
);
<|endoftext|>


<commit_before>// author: Buck Clay (dev@buckclay.com)
// date: 2013-12-25

// TODO: something is causing it to be terribly slow...
// TODO: come back to load file, previous file is gone... (state loss)

/**
 * Clear the command queue.
 */
function clearCommandQueue() {
  window.workspaceCommandQueue = [];
  window.workspacePendingAck = false;
  $("#lbl-enqueued-command-count").text(0);
}

$(document).ready(function() {
  // configure the console actions.
  $("#lnk-clear-log").click(function(e) {
    $("#console-log").html("");
  });
  $("#lnk-clear-command-queue").click(clearCommandQueue);
  $("#lnk-clear-ack-block").click(function(e) {
    window.workspacePendingAck = false;
  });
});

// Configure AngularJS.
var app = angular.module('gcodeSender', ['ui.router', 'luegg.directives', 'cfp.hotkeys']);

app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('about', {url: "/about", templateUrl: "about.html"})
    .state('settings', {
      url: "/settings",
      templateUrl: "settings.html",
      controller: "settingsCtrl"})
    .state('loadfile', {
      url: "/loadfile",
      templateUrl: "loadfile.html",
      controller: "loadFileCtrl"})
    .state('controlpanel', {
      url: "/controlpanel",
      templateUrl: "controlpanel.html",
      controller: "controlPanelCtrl"})
    ;
});

app.controller('mainCtrl', function($scope, $state, $window, hotkeys,
    settingsService, machineService, warningService, fileService) {
  settingsService.load();
  $state.go("controlpanel");

  $scope.$state = $state;
  $scope.warningService = warningService;
  $scope.machineService = machineService;

  /**
   * Connect to the configured serial port.
   */
  $scope.connect = function() {
    // If there is no connection port, send the user to the settings path.
    if (!settingsService.settings.workspace_port) {
      $state.go("settings");
      return;
    }

    machineService.connect(settingsService.settings.workspace_port,
        settingsService.settings.workspace_baud);
  };
  $scope.disconnect = machineService.disconnect;

  // Setup the drag-and-drop listeners.
  document.body.addEventListener('dragover', function(e) {
    e.stopPropagation();
    e.preventDefault();
    $state.go("loadfile");
  }, false);

  // Setup resize events.
  $window.addEventListener('resize', function() {
    $scope.$broadcast('resize');
  });

  // Global keyboard commands.
  hotkeys.add({
    combo: 'mod+o',
    description: 'open file',
    callback: function() {
      $state.go("loadfile");
      fileService.openFile();
    }
  });
  hotkeys.add({
    combo: 'mod+k',
    description: 'connect/disconnect',
    callback: function() {
      if (machineService.isConnected) {
        $scope.disconnect();
      } else {
        $scope.connect();
      }
    }
  });
  hotkeys.add({
    combo: 'mod+1',
    description: 'show control panel',
    callback: function() {$state.go('controlpanel');}
  });
  hotkeys.add({
    combo: 'mod+2',
    description: 'show load file',
    callback: function() {$state.go('loadfile');}
  });
  hotkeys.add({
    combo: 'mod+3',
    description: 'show settings',
    callback: function() {$state.go('settings');}
  });
  hotkeys.add({
    combo: 'mod+4',
    description: 'show about',
    callback: function() {$state.go('about');}
  });
});
<commit_msg>Remove some dead code<commit_after>// author: Buck Clay (dev@buckclay.com)
// date: 2013-12-25

// Configure AngularJS.
var app = angular.module('gcodeSender', ['ui.router', 'luegg.directives', 'cfp.hotkeys']);

app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('about', {url: "/about", templateUrl: "about.html"})
    .state('settings', {
      url: "/settings",
      templateUrl: "settings.html",
      controller: "settingsCtrl"})
    .state('loadfile', {
      url: "/loadfile",
      templateUrl: "loadfile.html",
      controller: "loadFileCtrl"})
    .state('controlpanel', {
      url: "/controlpanel",
      templateUrl: "controlpanel.html",
      controller: "controlPanelCtrl"})
    ;
});

app.controller('mainCtrl', function($scope, $state, $window, hotkeys,
    settingsService, machineService, warningService, fileService) {
  settingsService.load();
  $state.go("controlpanel");

  $scope.$state = $state;
  $scope.warningService = warningService;
  $scope.machineService = machineService;

  /**
   * Connect to the configured serial port.
   */
  $scope.connect = function() {
    // If there is no connection port, send the user to the settings path.
    if (!settingsService.settings.workspace_port) {
      $state.go("settings");
      return;
    }

    machineService.connect(settingsService.settings.workspace_port,
        settingsService.settings.workspace_baud);
  };
  $scope.disconnect = machineService.disconnect;

  // Setup the drag-and-drop listeners.
  document.body.addEventListener('dragover', function(e) {
    e.stopPropagation();
    e.preventDefault();
    $state.go("loadfile");
  }, false);

  // Setup resize events.
  $window.addEventListener('resize', function() {
    $scope.$broadcast('resize');
  });

  // Global keyboard commands.
  hotkeys.add({
    combo: 'mod+o',
    description: 'open file',
    callback: function() {
      $state.go("loadfile");
      fileService.openFile();
    }
  });
  hotkeys.add({
    combo: 'mod+k',
    description: 'connect/disconnect',
    callback: function() {
      if (machineService.isConnected) {
        $scope.disconnect();
      } else {
        $scope.connect();
      }
    }
  });
  hotkeys.add({
    combo: 'mod+1',
    description: 'show control panel',
    callback: function() {$state.go('controlpanel');}
  });
  hotkeys.add({
    combo: 'mod+2',
    description: 'show load file',
    callback: function() {$state.go('loadfile');}
  });
  hotkeys.add({
    combo: 'mod+3',
    description: 'show settings',
    callback: function() {$state.go('settings');}
  });
  hotkeys.add({
    combo: 'mod+4',
    description: 'show about',
    callback: function() {$state.go('about');}
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

// TODO: Show headers.
// TODO: Show HTTPS.
// TODO: Show OAuth.
// TODO: Show query parameter enums.
// TODO: Show query parameter default values.

var _ = require('lodash')
var marked = require('marked')
var handlebars = require('handlebars')
var hljs = require('highlight.js')
var raml = require('raml-parser')
var path = require('path')
var fs = require('fs')
var pkg = require('../package')

var STATUS_CODES = require('../status-codes')

var config = {
    version: pkg.version
}

var JSON_INDENT_SIZE = 2
function prettyJson(x) {
    return JSON.stringify(x, null, JSON_INDENT_SIZE)
}

// Try to pretty print a JSON string, falling back to the original if there's a
// parse error.
function tryPrettyJson(x) {
    try {
        return prettyJson(JSON.parse(x))
    } catch (e) {
        return x
    }
}

// Print error and exit 1 so we can break automated builds and such.
function die(message) {
    console.error(message)
    process.exit(1)
}

// Load file from templates/ directory.
function loadTemplate(x) {
    var f = path.join(__dirname, '..', 'templates', x)
    return fs.readFileSync(f, 'utf-8')
}

// Flatten RAML's nested hierarchy of traits and resources.
function flattenHierarchy(root) {
    var title = root.title
    var traits = traitsToObject(root.traits)
    var resources = flattenResources(root, root.traits)
    return {
        title: root.title,
        traits: traits,
        resources: resources
    }
}

// Convert traits from a list of objects to an object.
function traitsToObject(traits) {
    return _.reduce(traits, function(acc, obj) {
        var key = Object.keys(obj)[0]
        acc[key] = obj[key]
        return acc
    }, {})
}

// Flatten RAML's nested resources into a list of resources.
function flattenResources(res, traits) {
    var xs = []
    function recur(parents, res) {
        if (!res) {
            return
        }
        var clean = _.extend({}, res)
        delete clean.resources
        clean.methods = flattenMethods(res.methods)
        clean.basePath = _.pluck(parents, 'relativeUri').join('')
        clean.path = res.relativeUri
        clean.fullPath = clean.basePath + clean.path
        xs.push(clean)
        var newParents = parents.concat([res])
        _.forEach(res.resources, function(r) {
            recur(newParents, r)
        })
    }
    recur([], res)
    return _.sortBy(xs, 'fullPath')
}

// Flatten all the examples for a resource into a list, or generate a JSON body
// example based on the declared parameters, filling in junk data.
function makeExamplesOf(obj) {
    if (obj.body) {
        return _.map(_.pluck(_.values(obj.body), 'example'), tryPrettyJson)
    }
}

// Flattens the various methods defined on a resource, so we can have a list at
// the end, making it easy for the template.
function flattenMethods(methods) {
    return _.map(methods, function(objForMethod) {
        var obj = _.extend({}, objForMethod)
        var methodName = objForMethod.method
        obj.requestExamples = makeExamplesOf(obj)
        obj.responses = _.map(objForMethod.responses, function(objForCode, code) {
            var obj = {}
            _.forEach(objForCode, function(objForBody, body) {
                _.forEach(objForBody, function(objForRespType, respType) {
                    obj.example = objForRespType.example
                    obj.code = code
                    obj.method = methodName
                })
            })
            return obj
        })
        return obj
    })
}

// Load all Handlebars helpers and partials.
function registerHelpersAndPartials() {
    handlebars.registerHelper('json', function(data) {
        var out = hljs.highlight('json', prettyJson(data))
        return new handlebars.SafeString(
            '
'
            + out.value
            + '
'
        )
    })
    handlebars.registerHelper('response_code', function(num) {
        var n = Math.floor(num / 100)
        var s = num + ' ' + STATUS_CODES[num]
        return new handlebars.SafeString(
            ''
            + handlebars.escapeExpression(s)
            + ''
        )
    })
    handlebars.registerHelper('json_from_string', function(data) {
        if (data === undefined) {
            return ''
        }
        var err = ''
        try {
            data = prettyJson(JSON.parse(data))
        } catch (e) {
            err = JSON_PARSE_ERROR
        }
        var out = hljs.highlight('json', data)
        return new handlebars.SafeString(
            err
            + '
'
            + out.value
            + '
'
        )
    })
    handlebars.registerHelper('markdown', function(md) {
        return md ? new handlebars.SafeString(marked(md)) : ''
    })
    handlebars.registerHelper('upper_case', function(s) {
        return s.toUpperCase()
    })
    handlebars.registerPartial('resource', RESOURCE)
    handlebars.registerPartial('table_of_contents', TABLE_OF_CONTENTS)
    handlebars.registerPartial('style', STYLE)
}

// Curried form of tap for injecting side-effects into a pipeline.
function tap(f) {
    return function(o) {
        f(o)
        return o
    }
}

// Grab input RAML filename.
var args = process.argv.slice(2)
if (args.length !== 1) {
    die('Expected one argument: input RAML file')
}
var input = args[0]

// Load template files.
var INDEX = loadTemplate('index.handlebars')
var RESOURCE = loadTemplate('resource.handlebars')
var TABLE_OF_CONTENTS = loadTemplate('table_of_contents.handlebars')
var STYLE = loadTemplate('style.css')
var JSON_PARSE_ERROR = loadTemplate('invalid_json.html')
var toHtml = handlebars.compile(INDEX, {
    preventIndent: true
})

registerHelpersAndPartials()

function write(x) {
    process.stdout.write(x)
}

function parseFail(error) {
    die('Error parsing: ' + error)
}

// Ensure that uncaught exceptions are eventually shown in the console.
function throwLater(e) {
    setTimeout(function() { throw e }, 0)
}

// Load the RAML and output the HTML.
raml
    .loadFile(input)
    .catch(parseFail)
    .then(flattenHierarchy)
    .then(tap(function(obj) { obj.config = config }))
    .then(toHtml)
    .then(write)
    .catch(throwLater)
<commit_msg>Addresses some of the PR concerns<commit_after>#!/usr/bin/env node
'use strict'

// TODO: Show headers.
// TODO: Show HTTPS.
// TODO: Show OAuth.
// TODO: Show query parameter enums.
// TODO: Show query parameter default values.

var _ = require('lodash')
var marked = require('marked')
var handlebars = require('handlebars')
var hljs = require('highlight.js')
var raml = require('raml-parser')
var path = require('path')
var fs = require('fs')
var pkg = require('../package')

var STATUS_CODES = require('../status-codes')

var config = {
    version: pkg.version
}

var JSON_INDENT_SIZE = 2
function prettyJson(x) {
    return JSON.stringify(x, null, JSON_INDENT_SIZE)
}

// Try to pretty print a JSON string, falling back to the original if there's a
// parse error.
function tryPrettyJson(x) {
    try {
        return prettyJson(JSON.parse(x))
    } catch (e) {
        return x
    }
}

// Print error and exit 1 so we can break automated builds and such.
function die(message) {
    console.error(message)
    process.exit(1)
}

// Load file from templates/ directory.
function loadTemplate(x) {
    var f = path.join(__dirname, '..', 'templates', x)
    return fs.readFileSync(f, 'utf-8')
}

// Flatten RAML's nested hierarchy of traits and resources.
function flattenHierarchy(root) {
    var title = root.title
    var traits = traitsToObject(root.traits)
    var resources = flattenResources(root, root.traits)
    return {
        title: root.title,
        traits: traits,
        resources: resources
    }
}

// Convert traits from a list of objects to an object.
function traitsToObject(traits) {
    return _.reduce(traits, function(acc, obj) {
        var key = Object.keys(obj)[0]
        acc[key] = obj[key]
        return acc
    }, {})
}

// Flatten RAML's nested resources into a list of resources.
function flattenResources(res, traits) {
    var xs = []
    function recur(parents, res) {
        if (!res) {
            return
        }
        var clean = _.extend({}, res)
        delete clean.resources
        clean.methods = flattenMethods(res.methods)
        clean.basePath = _.pluck(parents, 'relativeUri').join('')
        clean.path = res.relativeUri
        clean.fullPath = clean.basePath + clean.path
        xs.push(clean)
        var newParents = parents.concat([res])
        _.forEach(res.resources, function(r) {
            recur(newParents, r)
        })
    }
    recur([], res)
    return _.sortBy(xs, 'fullPath')
}

// Flatten all the examples for a resource into a list, or generate a JSON body
// example based on the declared parameters, filling in junk data.
function makeExamplesOf(obj) {
    if (obj.body) {
        return _.map(_.pluck(_.values(obj.body), 'example'), tryPrettyJson)
    }
}

// Flattens the various methods defined on a resource, so we can have a list at
// the end, making it easy for the template.
function flattenMethods(methods) {
    return _.map(methods, function(objForMethod) {
        var obj = _.extend({}, objForMethod)
        var methodName = objForMethod.method
        obj.requestExamples = makeExamplesOf(obj)
        obj.responses = _.map(objForMethod.responses, function(objForCode, code) {
            var obj = {}
            _.forEach(objForCode, function(objForBody, body) {
                _.forEach(objForBody, function(objForRespType, respType) {
                    obj.example = objForRespType.example
                    obj.code = code
                    obj.method = methodName
                })
            })
            return obj
        })
        return obj
    })
}

// Load all Handlebars helpers and partials.
function registerHelpersAndPartials() {
    handlebars.registerHelper('json', function(data) {
        var out = hljs.highlight('json', prettyJson(data))
        return new handlebars.SafeString(
            '
'
            + out.value
            + '
'
        )
    })
    handlebars.registerHelper('response_code', function(num) {
        var n = Math.floor(num / 100)
        var s = num + ' ' + STATUS_CODES[num]
        return new handlebars.SafeString(
            ''
            + handlebars.escapeExpression(s)
            + ''
        )
    })
    handlebars.registerHelper('json_from_string', function(data) {
        if (data === undefined) {
            return ''
        }
        var err = ''
        try {
            data = prettyJson(JSON.parse(data))
        } catch (e) {
            err = JSON_PARSE_ERROR
        }
        var out = hljs.highlight('json', data)
        return new handlebars.SafeString(
            err
            + '
'
            + out.value
            + '
'
        )
    })
    handlebars.registerHelper('markdown', function(md) {
        return md ? new handlebars.SafeString(marked(md)) : ''
    })
    handlebars.registerHelper('upper_case', _.method('toUpperCase'))
    handlebars.registerPartial('resource', RESOURCE)
    handlebars.registerPartial('table_of_contents', TABLE_OF_CONTENTS)
    handlebars.registerPartial('style', STYLE)
}

// Curried form of tap for injecting side-effects into a pipeline.
function tap(f) {
    return function(o) {
        f(o)
        return o
    }
}

// Grab input RAML filename.
var args = process.argv.slice(2)
if (args.length !== 1) {
    die('Expected one argument: input RAML file')
}
var input = args[0]

// Load template files.
var INDEX = loadTemplate('index.handlebars')
var RESOURCE = loadTemplate('resource.handlebars')
var TABLE_OF_CONTENTS = loadTemplate('table_of_contents.handlebars')
var STYLE = loadTemplate('style.css')
var JSON_PARSE_ERROR = loadTemplate('invalid_json.html')
var toHtml = handlebars.compile(INDEX, {
    preventIndent: true
})

registerHelpersAndPartials()

function write(x) {
    process.stdout.write(x)
}

function parseFail(error) {
    die('Error parsing: ' + error)
}

// Ensure that uncaught exceptions are eventually shown in the console.
function throwLater(e) {
    setTimeout(function() { throw e }, 0)
}

// Load the RAML and output the HTML.
raml
    .loadFile(input)
    .catch(parseFail)
    .then(flattenHierarchy)
    .then(function(obj) {
        return _.extend(obj, { config: config })
    })
    .then(toHtml)
    .then(write)
    .catch(throwLater)
<|endoftext|>


<commit_before>AFRAME.APAINTER = {
  version: 1,
  brushes: {},
  registerBrush: function (name, definition) {
    var proto = {};

    // Format definition object to prototype object.
    Object.keys(definition).forEach(function (key) {
      proto[key] = {
        value: definition[key],
        writable: true
      };
    });

    if (this.brushes[name]) {
      throw new Error('The brush `' + name + '` has been already registered. ' +
                      'Check that you are not loading two versions of the same brush ' +
                      'or two different brushes of the same name.');
    }

    var BrushInterface = function () {};

    BrushInterface.prototype = {
      reset: function () {},
      tick: function (timeoffset, delta) {},
      addPoint: function (position, rotation, pointerPosition, pressure, timestamp) {},
      getBinary: function () {
        // Color = 3*4 = 12
        // NumPoints   =  4
        // Brush index =  1
        // ----------- = 21
        // [Point] = vector3 + quat + pressure + timestamp = (3+4+1+1)*4 = 36
        var bufferSize = 21 + (36 * this.data.points.length);
        var binaryManager = new BinaryManager(new ArrayBuffer(bufferSize));
        binaryManager.writeUint8(AFRAME.APAINTER.getUsedBrushes().indexOf(this.brushName));  // brush index
        binaryManager.writeColor(this.data.color);    // color
        binaryManager.writeFloat32(this.data.size);   // brush size

        // Number of points
        binaryManager.writeUint32(this.data.points.length);

        // Points
        for (var i = 0; i < this.data.points.length; i++) {
          var point = this.data.points[i];
          binaryManager.writeFloat32Array(point.position.toArray());
          binaryManager.writeFloat32Array(point.rotation.toArray());
          binaryManager.writeFloat32(point.pressure);
          binaryManager.writeUint32(point.timestamp);
        }
        return binaryManager.getDataView();
      }
    };

    function wrapInit (initMethod) {
      return function init (color, brushSize) {
        this.data = {
          points: [],
          size: brushSize,
          prevPoint: null,
          numPoints: 0,
          maxPoints: 1000,
          color: color.clone()
        };
        initMethod.call(this, color, brushSize);
      };
    }

    function wrapAddPoint (addPointMethod) {
      return function addPoint (position, rotation, pointerPosition, pressure, timestamp) {
        if (this.data.prevPoint && this.data.prevPoint.equals(position)) {
          return;
        }
        this.data.prevPoint = position.clone();

        this.data.numPoints++;
        this.data.points.push({
          'position': position,
          'rotation': rotation,
          'pressure': pressure,
          'timestamp': timestamp
        });
        addPointMethod.call(this, position, rotation, pointerPosition, pressure, timestamp);
      };
    }

    var NewBrush = function () {};
    NewBrush.prototype = Object.create(BrushInterface.prototype, proto);
    NewBrush.prototype.brushName = name;
    NewBrush.prototype.constructor = NewBrush;
    NewBrush.prototype.init = wrapInit(NewBrush.prototype.init);
    NewBrush.prototype.addPoint = wrapAddPoint(NewBrush.prototype.addPoint);
    this.brushes[name] = NewBrush;

    console.log('New brush registered `' + name + '`');
    NewBrush.used = false; // Used to know which brushes have been used on the drawing
    return NewBrush;
  },
  getUsedBrushes: function () {
    return Object.keys(AFRAME.APAINTER.brushes)
      .filter(function (name){ return AFRAME.APAINTER.brushes[name].used; });
  },
  getBrushByName: function (name) {
    return this.brushes[name];
  }
};
<commit_msg>Added radiusThreshold<commit_after>AFRAME.APAINTER = {
  version: 1,
  brushes: {},
  registerBrush: function (name, definition) {
    var proto = {};

    // Format definition object to prototype object.
    Object.keys(definition).forEach(function (key) {
      proto[key] = {
        value: definition[key],
        writable: true
      };
    });

    if (this.brushes[name]) {
      throw new Error('The brush `' + name + '` has been already registered. ' +
                      'Check that you are not loading two versions of the same brush ' +
                      'or two different brushes of the same name.');
    }

    var BrushInterface = function () {};

    BrushInterface.prototype = {
      radiusThreshold: 0,
      reset: function () {},
      tick: function (timeoffset, delta) {},
      addPoint: function (position, rotation, pointerPosition, pressure, timestamp) {},
      getBinary: function () {
        // Color = 3*4 = 12
        // NumPoints   =  4
        // Brush index =  1
        // ----------- = 21
        // [Point] = vector3 + quat + pressure + timestamp = (3+4+1+1)*4 = 36
        var bufferSize = 21 + (36 * this.data.points.length);
        var binaryManager = new BinaryManager(new ArrayBuffer(bufferSize));
        binaryManager.writeUint8(AFRAME.APAINTER.getUsedBrushes().indexOf(this.brushName));  // brush index
        binaryManager.writeColor(this.data.color);    // color
        binaryManager.writeFloat32(this.data.size);   // brush size

        // Number of points
        binaryManager.writeUint32(this.data.points.length);

        // Points
        for (var i = 0; i < this.data.points.length; i++) {
          var point = this.data.points[i];
          binaryManager.writeFloat32Array(point.position.toArray());
          binaryManager.writeFloat32Array(point.rotation.toArray());
          binaryManager.writeFloat32(point.pressure);
          binaryManager.writeUint32(point.timestamp);
        }
        return binaryManager.getDataView();
      }
    };

    function wrapInit (initMethod) {
      return function init (color, brushSize) {
        this.data = {
          points: [],
          size: brushSize,
          prevPoint: null,
          numPoints: 0,
          maxPoints: 1000,
          color: color.clone()
        };
        initMethod.call(this, color, brushSize);
      };
    }

    function wrapAddPoint (addPointMethod) {
      return function addPoint (position, rotation, pointerPosition, pressure, timestamp) {
        if (this.data.prevPoint
            && this.data.prevPoint.distanceTo(position) <= this.radiusThreshold) {
          return;
        }
        this.data.prevPoint = position.clone();

        this.data.numPoints++;
        this.data.points.push({
          'position': position,
          'rotation': rotation,
          'pressure': pressure,
          'timestamp': timestamp
        });
        addPointMethod.call(this, position, rotation, pointerPosition, pressure, timestamp);
      };
    }

    var NewBrush = function () {};
    NewBrush.prototype = Object.create(BrushInterface.prototype, proto);
    NewBrush.prototype.brushName = name;
    NewBrush.prototype.constructor = NewBrush;
    NewBrush.prototype.init = wrapInit(NewBrush.prototype.init);
    NewBrush.prototype.addPoint = wrapAddPoint(NewBrush.prototype.addPoint);
    this.brushes[name] = NewBrush;

    console.log('New brush registered `' + name + '`');
    NewBrush.used = false; // Used to know which brushes have been used on the drawing
    return NewBrush;
  },
  getUsedBrushes: function () {
    return Object.keys(AFRAME.APAINTER.brushes)
      .filter(function (name){ return AFRAME.APAINTER.brushes[name].used; });
  },
  getBrushByName: function (name) {
    return this.brushes[name];
  }
};
<|endoftext|>


<commit_before>import 'babel-polyfill';
import environment from './environment';
import Backend from 'i18next-xhr-backend';

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .feature('resources')
    .plugin('aurelia-i18n', (instance) => {
      TCustomAttribute.configureAliases(['t']);

      instance.i18next.use(Backend.with(aurelia.loader));

      return instance.setup({
        backend: {
          loadPath: './lang/{{lng}}.json'
        },
        attributes: aliases,
        lng: 'fi',
        fallbackLng: 'en',
        debug: environment.debug
      });
    });

  if (environment.debug) {
    aurelia.use.developmentLogging();
  }

  if (environment.testing) {
    aurelia.use.plugin('aurelia-testing');
  }

  aurelia.start().then(() => aurelia.setRoot());
}
<commit_msg>Fix I18n setup<commit_after>import 'babel-polyfill';
import {TCustomAttribute, Backend} from 'aurelia-i18n';
import environment from './environment';

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .feature('resources')
    .plugin('aurelia-i18n', (instance) => {
      TCustomAttribute.configureAliases(['t']);

      instance.i18next.use(Backend.with(aurelia.loader));

      return instance.setup({
        backend: {
          loadPath: './lang/{{lng}}.json'
        },
        attributes: ['t'],
        lng: 'fi',
        fallbackLng: 'en',
        debug: environment.debug
      });
    });

  if (environment.debug) {
    aurelia.use.developmentLogging();
  }

  if (environment.testing) {
    aurelia.use.plugin('aurelia-testing');
  }

  aurelia.start().then(() => aurelia.setRoot());
}
<|endoftext|>


<commit_before>import fs from 'fs'
import split from 'split'
import eos from 'end-of-stream'

export default function(file) {
	var data = {
		file,
		includes: [],
		subs: [],
		funcs: [],
		lines: 0,
	}
	var inputStream = fs.createReadStream(file)
		.pipe(split())
		.on('data', line => {
			data.lines++
		})
	return new Promise((resolve, reject) => {
		eos(inputStream, err => err ? reject(err) : resolve(data))
	})
}
<commit_msg>Lines split over multiple lines (with '_') are now concatenated correctly<commit_after>import fs from 'fs'
import split from 'split'
import eos from 'end-of-stream'

export default function(file) {
	var data = {
		file,
		includes: [],
		subs: [],
		funcs: [],
	}

	var currentLine = ''
	var inputStream = fs.createReadStream(file)
		.pipe(split())
		.on('data', line => {
			if(line.endsWith('_')) {
				currentLine += line.substring(0, line.length - 1)
				return
			}
			currentLine += line
			console.log('line:', currentLine)

			currentLine = ''
		})

	return new Promise((resolve, reject) => {
		eos(inputStream, err => err ? reject(err) : resolve(data))
	})
}
<|endoftext|>


<commit_before>import React from 'react';
import Component from './component';
import Clusters from './Clusters';
import Pin from './Pin';
import {Marker, InfoBox} from './elements';

export {
	Pin,
	Component,
	Clusters
};

export function MarkerPin(props) {
	let pinProps = {
		pos: props.pos,
		offset: props.offset,
		zoom: props.zoom
	};
	return (
		<Pin {...pinProps}>
			<Marker {...props}>{props.children}</Marker>
		</Pin>
	);
}

export function InfoBoxPin(props) {
	let pinProps = {
		pos: props.pos,
		offset: props.offset,
		zoom: props.zoom,
		onClick: props.onClick
	};
	return (
		<Pin {...pinProps}>
			<InfoBox {...props}>{props.children}</InfoBox>
		</Pin>
	);
}
<commit_msg>Pinned objects cleanup<commit_after>import React from 'react';
import Component from './component';
import Clusters from './Clusters';
import Pin from './Pin';
import {Marker, InfoBox} from './elements';

export {
	Pin,
	Component,
	Clusters
};

function pinned(Component) {
	return function(props) {
		let pinProps = {
			pos: props.pos,
			offset: props.offset,
			zoom: props.zoom,
			onClick: props.onClick
		};
		return (
			<Pin {...pinProps}>
				<Component {...props}>{props.children}</Component>
			</Pin>
		);
	};
}

export let MarkerPin = pinned(Marker);
export let InfoBoxPin = pinned(InfoBox);
<|endoftext|>


<commit_before>/* eslint-disable no-use-before-define */

import * as AxiosUtils from '../utils/axios';
import * as DataApi from './DataApi';
import { DATA_API } from '../constants/ApiNames';

import {
  COUNT_PATH,
  ENTITY_DATA_PATH,
  TICKET_PATH,
  SET_PATH
} from '../constants/ApiPaths';

import {
  INVALID_PARAMS,
  INVALID_PARAMS_SS,
  INVALID_PARAMS_SS_EMPTY_ARRAY_ALLOWED,
  INVALID_PARAMS_SS_EMPTY_STRING_ALLOWED
} from '../utils/testing/Invalid';

import {
  genMockBaseUrl,
  genRandomString,
  genRandomUUID,
  getMockAxiosInstance
} from '../utils/testing/MockUtils';

import {
  assertApiShouldSendCorrectHttpRequest,
  testApiShouldNotThrowOnInvalidParameters,
  testApiShouldRejectOnInvalidParameters,
  testApiShouldReturnPromise,
  testApiShouldReturnNullOnInvalidParameters,
  testApiShouldSendCorrectHttpRequest,
  testApiShouldUseCorrectAxiosInstance
} from '../utils/testing/TestUtils';

/*
 * mocks
 */

const MOCK_BASE_URL = genMockBaseUrl();
const MOCK_FILE_TYPE = 'json';
const MOCK_ENTITY_SET_UUID = genRandomUUID();
const MOCK_PROPERTY_TYPE_UUID = genRandomUUID();
const MOCK_SYNC_UUID = genRandomUUID();
const MOCK_TICKET_UUID = genRandomUUID();

const MOCK_ENTITIES = {
  entityId_1: [
    {
      [`${genRandomUUID()}`]: ['value_1', 'value_2'],
      [`${genRandomUUID()}`]: ['value_3', 'value_4']
    }
  ]
};

jest.mock('../utils/axios');
AxiosUtils.getApiBaseUrl.mockImplementation(() => MOCK_BASE_URL);
AxiosUtils.getApiAxiosInstance.mockImplementation(() => getMockAxiosInstance());

/*
 * tests
 */

describe('DataApi', () => {

  afterEach(() => {
    jest.clearAllMocks();
  });

  getEntitySetData();
  getEntitySetDataFileUrl();
  createEntityData();
  storeEntityData();
  acquireSyncTicket();
  releaseSyncTicket();
  deleteEntityFromEntitySet();
  replaceEntityInEntitySet();
  replaceEntityInEntitySetUsingFqns();
  getEntitySetSize();
  getEntity();
});

function getEntitySetData() {

  describe('getEntitySetData()', () => {

    const apiToTest = DataApi.getEntitySetData;

    const validParams = [
      MOCK_ENTITY_SET_UUID,
      MOCK_SYNC_UUID,
      [MOCK_PROPERTY_TYPE_UUID]
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS_SS_EMPTY_STRING_ALLOWED,
      INVALID_PARAMS_SS_EMPTY_ARRAY_ALLOWED
    ];

    describe('should send a POST request with the correct params', () => {

      test('+syncId, +propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          MOCK_SYNC_UUID,
          [MOCK_PROPERTY_TYPE_UUID]
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          {
            syncId: MOCK_SYNC_UUID,
            properties: [MOCK_PROPERTY_TYPE_UUID]
          }
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

      test('+syncId, -propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          MOCK_SYNC_UUID,
          undefined
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          { syncId: MOCK_SYNC_UUID }
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

      test('-syncId, +propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          undefined,
          [MOCK_PROPERTY_TYPE_UUID]
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          { properties: [MOCK_PROPERTY_TYPE_UUID] }
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

      test('-syncId, -propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          {}
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

    });

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
  });
}

function getEntitySetDataFileUrl() {

  describe('getEntitySetDataFileUrl()', () => {

    const apiToTest = DataApi.getEntitySetDataFileUrl;

    const validParams = [
      MOCK_ENTITY_SET_UUID,
      MOCK_FILE_TYPE
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS
    ];

    test('should return the correct URL', () => {

      expect(DataApi.getEntitySetDataFileUrl(MOCK_ENTITY_SET_UUID, MOCK_FILE_TYPE)).toEqual(
        `${MOCK_BASE_URL}/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}?fileType=${MOCK_FILE_TYPE}`
      );
    });

    test('should correctly set the fileType query param as lowercase', () => {

      expect(DataApi.getEntitySetDataFileUrl(MOCK_ENTITY_SET_UUID, MOCK_FILE_TYPE.toUpperCase())).toEqual(
        `${MOCK_BASE_URL}/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}?fileType=${MOCK_FILE_TYPE}`
      );
    });

    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldReturnNullOnInvalidParameters(apiToTest, validParams, invalidParams);

  });
}

function createEntityData() {

  describe('createEntityData()', () => {

    const apiToTest = DataApi.createEntityData;

    const validParams = [
      MOCK_ENTITY_SET_UUID,
      MOCK_SYNC_UUID,
      MOCK_ENTITIES
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS_SS_EMPTY_STRING_ALLOWED,
      INVALID_PARAMS
    ];

    describe('should send a PUT request with the correct URL path and data when syncId is given', () => {

      test('+syncId', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          MOCK_SYNC_UUID,
          MOCK_ENTITIES
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}/${MOCK_SYNC_UUID}`,
          MOCK_ENTITIES
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'put');
      });

      test('-syncId', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          undefined,
          MOCK_ENTITIES
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          MOCK_ENTITIES
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'put');
      });

    });

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);

  });
}

function storeEntityData() {

  describe('storeEntityData()', () => {

    const apiToTest = DataApi.storeEntityData;

    const validParams = [
      MOCK_TICKET_UUID,
      MOCK_SYNC_UUID,
      MOCK_ENTITIES
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS_SS,
      INVALID_PARAMS
    ];

    const axiosParams = [
      `/${ENTITY_DATA_PATH}/${TICKET_PATH}/${MOCK_TICKET_UUID}/${MOCK_SYNC_UUID}`,
      MOCK_ENTITIES
    ];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'patch');
  });
}

function acquireSyncTicket() {

  describe('acquireSyncTicket()', () => {

    const apiToTest = DataApi.acquireSyncTicket;

    const validParams = [MOCK_ENTITY_SET_UUID, MOCK_SYNC_UUID];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS];
    const axiosParams = [`/${TICKET_PATH}/${MOCK_ENTITY_SET_UUID}/${MOCK_SYNC_UUID}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'post');
  });
}

function releaseSyncTicket() {

  describe('releaseSyncTicket()', () => {

    const apiToTest = DataApi.releaseSyncTicket;

    const validParams = [MOCK_TICKET_UUID];
    const invalidParams = [INVALID_PARAMS_SS];
    const axiosParams = [`/${TICKET_PATH}/${MOCK_TICKET_UUID}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'delete');
  });
}

function deleteEntityFromEntitySet() {

  describe('deleteEntityFromEntitySet()', () => {

    const apiToTest = DataApi.deleteEntityFromEntitySet;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();

    const validParams = [mockEntitySetId, mockEntityKeyId];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS];
    const axiosParams = [`/${ENTITY_DATA_PATH}/${mockEntitySetId}/${mockEntityKeyId}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'delete');
  });
}

function replaceEntityInEntitySet() {

  describe('replaceEntityInEntitySet()', () => {

    const apiToTest = DataApi.replaceEntityInEntitySet;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();
    const mockEntity = {
      [`${genRandomUUID()}`]: ['value_1', 'value_2']
    };

    // TODO: generate invalid params for the "entity" param

    const validParams = [mockEntitySetId, mockEntityKeyId, mockEntity];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS, INVALID_PARAMS];
    const axiosParams = [`/${SET_PATH}/${mockEntitySetId}/${mockEntityKeyId}`, mockEntity];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'put');
  });
}

function replaceEntityInEntitySetUsingFqns() {

  describe('replaceEntityInEntitySetUsingFqns()', () => {

    const apiToTest = DataApi.replaceEntityInEntitySetUsingFqns;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();
    const mockEntity = {
      [`${genRandomString()}.${genRandomString()}`]: ['value_1', 'value_2']
    };

    // TODO: generate invalid params for the "entity" param

    const validParams = [mockEntitySetId, mockEntityKeyId, mockEntity];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS, INVALID_PARAMS];
    const axiosParams = [`/${SET_PATH}/${mockEntitySetId}/${mockEntityKeyId}`, mockEntity];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'post');
  });
}

function getEntitySetSize() {

  describe('getEntitySetSize()', () => {

    const apiToTest = DataApi.getEntitySetSize;
    const mockEntitySetId = genRandomUUID();

    const validParams = [mockEntitySetId];
    const invalidParams = [INVALID_PARAMS_SS];
    const axiosParams = [`/${mockEntitySetId}/${COUNT_PATH}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'get');
  });
}

function getEntity() {

  describe('getEntity()', () => {

    const apiToTest = DataApi.getEntity;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();

    const validParams = [mockEntitySetId, mockEntityKeyId];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS];
    const axiosParams = [`/${mockEntitySetId}/${mockEntityKeyId}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'get');
  });
}
<commit_msg>+ more<commit_after>/* eslint-disable no-use-before-define */

import * as AxiosUtils from '../utils/axios';
import * as DataApi from './DataApi';
import { DATA_API } from '../constants/ApiNames';

import {
  COUNT_PATH,
  ENTITY_DATA_PATH,
  SET_PATH,
  TICKET_PATH
} from '../constants/ApiPaths';

import {
  INVALID_PARAMS,
  INVALID_PARAMS_SS,
  INVALID_PARAMS_SS_EMPTY_ARRAY_ALLOWED,
  INVALID_PARAMS_SS_EMPTY_STRING_ALLOWED
} from '../utils/testing/Invalid';

import {
  genMockBaseUrl,
  genRandomString,
  genRandomUUID,
  getMockAxiosInstance
} from '../utils/testing/MockUtils';

import {
  assertApiShouldSendCorrectHttpRequest,
  testApiShouldNotThrowOnInvalidParameters,
  testApiShouldRejectOnInvalidParameters,
  testApiShouldReturnPromise,
  testApiShouldReturnNullOnInvalidParameters,
  testApiShouldSendCorrectHttpRequest,
  testApiShouldUseCorrectAxiosInstance
} from '../utils/testing/TestUtils';

/*
 * mocks
 */

const MOCK_BASE_URL = genMockBaseUrl();
const MOCK_FILE_TYPE = 'json';
const MOCK_ENTITY_SET_UUID = genRandomUUID();
const MOCK_PROPERTY_TYPE_UUID = genRandomUUID();
const MOCK_SYNC_UUID = genRandomUUID();
const MOCK_TICKET_UUID = genRandomUUID();

const MOCK_ENTITIES = {
  entityId_1: [
    {
      [`${genRandomUUID()}`]: ['value_1', 'value_2'],
      [`${genRandomUUID()}`]: ['value_3', 'value_4']
    }
  ]
};

jest.mock('../utils/axios');
AxiosUtils.getApiBaseUrl.mockImplementation(() => MOCK_BASE_URL);
AxiosUtils.getApiAxiosInstance.mockImplementation(() => getMockAxiosInstance());

/*
 * tests
 */

describe('DataApi', () => {

  afterEach(() => {
    jest.clearAllMocks();
  });

  getEntitySetData();
  getEntitySetDataFileUrl();
  createEntityData();
  storeEntityData();
  acquireSyncTicket();
  releaseSyncTicket();
  deleteEntityFromEntitySet();
  replaceEntityInEntitySet();
  replaceEntityInEntitySetUsingFqns();
  getEntitySetSize();
  getEntity();
});

function getEntitySetData() {

  describe('getEntitySetData()', () => {

    const apiToTest = DataApi.getEntitySetData;

    const validParams = [
      MOCK_ENTITY_SET_UUID,
      MOCK_SYNC_UUID,
      [MOCK_PROPERTY_TYPE_UUID]
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS_SS_EMPTY_STRING_ALLOWED,
      INVALID_PARAMS_SS_EMPTY_ARRAY_ALLOWED
    ];

    describe('should send a POST request with the correct params', () => {

      test('+syncId, +propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          MOCK_SYNC_UUID,
          [MOCK_PROPERTY_TYPE_UUID]
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          {
            syncId: MOCK_SYNC_UUID,
            properties: [MOCK_PROPERTY_TYPE_UUID]
          }
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

      test('+syncId, -propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          MOCK_SYNC_UUID,
          undefined
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          { syncId: MOCK_SYNC_UUID }
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

      test('-syncId, +propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          undefined,
          [MOCK_PROPERTY_TYPE_UUID]
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          { properties: [MOCK_PROPERTY_TYPE_UUID] }
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

      test('-syncId, -propertyTypeIds', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          {}
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'post');
      });

    });

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
  });
}

function getEntitySetDataFileUrl() {

  describe('getEntitySetDataFileUrl()', () => {

    const apiToTest = DataApi.getEntitySetDataFileUrl;

    const validParams = [
      MOCK_ENTITY_SET_UUID,
      MOCK_FILE_TYPE
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS
    ];

    test('should return the correct URL', () => {

      expect(DataApi.getEntitySetDataFileUrl(MOCK_ENTITY_SET_UUID, MOCK_FILE_TYPE)).toEqual(
        `${MOCK_BASE_URL}/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}?fileType=${MOCK_FILE_TYPE}`
      );
    });

    test('should correctly set the fileType query param as lowercase', () => {

      expect(DataApi.getEntitySetDataFileUrl(MOCK_ENTITY_SET_UUID, MOCK_FILE_TYPE.toUpperCase())).toEqual(
        `${MOCK_BASE_URL}/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}?fileType=${MOCK_FILE_TYPE}`
      );
    });

    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldReturnNullOnInvalidParameters(apiToTest, validParams, invalidParams);

  });
}

function createEntityData() {

  describe('createEntityData()', () => {

    const apiToTest = DataApi.createEntityData;

    const validParams = [
      MOCK_ENTITY_SET_UUID,
      MOCK_SYNC_UUID,
      MOCK_ENTITIES
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS_SS_EMPTY_STRING_ALLOWED,
      INVALID_PARAMS
    ];

    describe('should send a PUT request with the correct URL path and data when syncId is given', () => {

      test('+syncId', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          MOCK_SYNC_UUID,
          MOCK_ENTITIES
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}/${MOCK_SYNC_UUID}`,
          MOCK_ENTITIES
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'put');
      });

      test('-syncId', () => {

        const apiInvocationParams = [
          MOCK_ENTITY_SET_UUID,
          undefined,
          MOCK_ENTITIES
        ];

        const expectedAxiosParams = [
          `/${ENTITY_DATA_PATH}/${MOCK_ENTITY_SET_UUID}`,
          MOCK_ENTITIES
        ];

        return assertApiShouldSendCorrectHttpRequest(apiToTest, apiInvocationParams, expectedAxiosParams, 'put');
      });

    });

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);

  });
}

function storeEntityData() {

  describe('storeEntityData()', () => {

    const apiToTest = DataApi.storeEntityData;

    const validParams = [
      MOCK_TICKET_UUID,
      MOCK_SYNC_UUID,
      MOCK_ENTITIES
    ];

    const invalidParams = [
      INVALID_PARAMS_SS,
      INVALID_PARAMS_SS,
      INVALID_PARAMS
    ];

    const axiosParams = [
      `/${ENTITY_DATA_PATH}/${TICKET_PATH}/${MOCK_TICKET_UUID}/${MOCK_SYNC_UUID}`,
      MOCK_ENTITIES
    ];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'patch');
  });
}

function acquireSyncTicket() {

  describe('acquireSyncTicket()', () => {

    const apiToTest = DataApi.acquireSyncTicket;

    const validParams = [MOCK_ENTITY_SET_UUID, MOCK_SYNC_UUID];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS];
    const axiosParams = [`/${TICKET_PATH}/${MOCK_ENTITY_SET_UUID}/${MOCK_SYNC_UUID}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'post');
  });
}

function releaseSyncTicket() {

  describe('releaseSyncTicket()', () => {

    const apiToTest = DataApi.releaseSyncTicket;

    const validParams = [MOCK_TICKET_UUID];
    const invalidParams = [INVALID_PARAMS_SS];
    const axiosParams = [`/${TICKET_PATH}/${MOCK_TICKET_UUID}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'delete');
  });
}

function deleteEntityFromEntitySet() {

  describe('deleteEntityFromEntitySet()', () => {

    const apiToTest = DataApi.deleteEntityFromEntitySet;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();

    const validParams = [mockEntitySetId, mockEntityKeyId];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS];
    const axiosParams = [`/${ENTITY_DATA_PATH}/${mockEntitySetId}/${mockEntityKeyId}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'delete');
  });
}

function replaceEntityInEntitySet() {

  describe('replaceEntityInEntitySet()', () => {

    const apiToTest = DataApi.replaceEntityInEntitySet;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();
    const mockEntity = {
      [`${genRandomUUID()}`]: ['value_1', 'value_2']
    };

    // TODO: generate invalid params for the "entity" param

    const validParams = [mockEntitySetId, mockEntityKeyId, mockEntity];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS, INVALID_PARAMS];
    const axiosParams = [`/${SET_PATH}/${mockEntitySetId}/${mockEntityKeyId}`, mockEntity];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'put');
  });
}

function replaceEntityInEntitySetUsingFqns() {

  describe('replaceEntityInEntitySetUsingFqns()', () => {

    const apiToTest = DataApi.replaceEntityInEntitySetUsingFqns;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();
    const mockEntity = {
      [`${genRandomString()}.${genRandomString()}`]: ['value_1', 'value_2']
    };

    // TODO: generate invalid params for the "entity" param

    const validParams = [mockEntitySetId, mockEntityKeyId, mockEntity];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS, INVALID_PARAMS];
    const axiosParams = [`/${SET_PATH}/${mockEntitySetId}/${mockEntityKeyId}`, mockEntity];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'post');
  });
}

function getEntitySetSize() {

  describe('getEntitySetSize()', () => {

    const apiToTest = DataApi.getEntitySetSize;
    const mockEntitySetId = genRandomUUID();

    const validParams = [mockEntitySetId];
    const invalidParams = [INVALID_PARAMS_SS];
    const axiosParams = [`/${mockEntitySetId}/${COUNT_PATH}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'get');
  });
}

function getEntity() {

  describe('getEntity()', () => {

    const apiToTest = DataApi.getEntity;
    const mockEntitySetId = genRandomUUID();
    const mockEntityKeyId = genRandomUUID();

    const validParams = [mockEntitySetId, mockEntityKeyId];
    const invalidParams = [INVALID_PARAMS_SS, INVALID_PARAMS_SS];
    const axiosParams = [`/${mockEntitySetId}/${mockEntityKeyId}`];

    testApiShouldReturnPromise(apiToTest, validParams);
    testApiShouldUseCorrectAxiosInstance(apiToTest, validParams, DATA_API);
    testApiShouldNotThrowOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldRejectOnInvalidParameters(apiToTest, validParams, invalidParams);
    testApiShouldSendCorrectHttpRequest(apiToTest, validParams, axiosParams, 'get');
  });
}
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import Resource from 'vue-resource'
// import { domain, fromNow } from './filters'
import App from './components/App.vue'
import Homepage from './components/Homepage.vue'
import EUMatches from './components/EUMatches.vue'
import Map from './components/Map.vue'
import Leaderboard from './components/Leaderboard.vue'

// install router
Vue.use(Router)
// install resource, for http requests
Vue.use(Resource)

// register filters globally
// Vue.filter('fromNow', fromNow)
// Vue.filter('domain', domain)

Vue.directive('progress', {
  bind: function () {},
  update: function (value, old) {
    // The directive may be called before the element have been upgraded
    window.componentHandler.upgradeElement(this.el)
    this.el.MaterialProgress.setProgress(value)
  }
})

Vue.directive('mdl', {
  bind: function () {
    window.componentHandler.upgradeElement(this.el)
  }
})

// routing
var router = new Router({hashbang: false})

router.map({
  '/na': {
    component: Homepage,
    pageTitle: 'North American Matches',
    region: '1-'
  },
  '/eu': {
    component: EUMatches,
    pageTitle: 'European Matches',
    region: '2-'
  },
  '/map': {
    component: Map,
    pageTitle: 'Live Map'
  },
  '/map/:server': {
    component: Map,
    pageTitle: 'Live Map'
  },
  '/leaderboard': {
    component: Leaderboard,
    pageTitle: 'Leaderboard'
  }
})

/**
 * uncomment if want page to go back to top..
 * TODO: Maybe animate this?
 */

/*router.afterEach(function () {
  console.log('hi')
  var _router_el = document.getElementById('router_view')
  _router_el.scrollTop = 0
})*/

router.redirect({
  '*': '/na'
})

router.start(App, '#app')
<commit_msg>Add route for the match due<commit_after>import Vue from 'vue'
import Router from 'vue-router'
import Resource from 'vue-resource'
// import { domain, fromNow } from './filters'
import App from './components/App.vue'
import Homepage from './components/Homepage.vue'
import EUMatches from './components/EUMatches.vue'
import Map from './components/Map.vue'
import Leaderboard from './components/Leaderboard.vue'
import Match from './components/Match.vue'

// install router
Vue.use(Router)
// install resource, for http requests
Vue.use(Resource)

// register filters globally
// Vue.filter('fromNow', fromNow)
// Vue.filter('domain', domain)

Vue.directive('progress', {
  bind: function () {},
  update: function (value, old) {
    // The directive may be called before the element have been upgraded
    window.componentHandler.upgradeElement(this.el)
    this.el.MaterialProgress.setProgress(value)
  }
})

Vue.directive('mdl', {
  bind: function () {
    window.componentHandler.upgradeElement(this.el)
  }
})

// routing
var router = new Router({hashbang: false})

router.map({
  '/na': {
    component: Homepage,
    pageTitle: 'North American Matches',
    region: '1-'
  },
  '/eu': {
    component: EUMatches,
    pageTitle: 'European Matches',
    region: '2-'
  },
  '/map': {
    component: Map,
    pageTitle: 'Live Map'
  },
  '/map/:server': {
    component: Map,
    pageTitle: 'Live Map'
  },
  '/leaderboard': {
    component: Leaderboard,
    pageTitle: 'Leaderboard'
  },
  '/match/:matchid': {
    component: Match,
    pageTitle: 'Match Details'
  }
})

/**
 * uncomment if want page to go back to top..
 * TODO: Maybe animate this?
 */

/*router.afterEach(function () {
  console.log('hi')
  var _router_el = document.getElementById('router_view')
  _router_el.scrollTop = 0
})*/

router.redirect({
  '*': '/na'
})

router.start(App, '#app')
<|endoftext|>


<commit_before>import html from './html';
import registry from '../global/registry';

function render (elem) {
  registry.find(elem).forEach(component => component.render && component.render(elem));
}

render.html = html;

export default render;
<commit_msg>Fixes #399. Fix relative path.<commit_after>import html from './html';
import registry from '../../global/registry';

function render (elem) {
  registry.find(elem).forEach(component => component.render && component.render(elem));
}

render.html = html;

export default render;
<|endoftext|>