<commit_before>// @flow

import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import { connect } from 'react-redux';

import {
    isNarrowAspectRatio,
    makeAspectRatioAware
} from '../../base/aspect-ratio';
import { Container } from '../../base/react';

import Thumbnail from './Thumbnail';
import { styles } from './_';

/**
 * Implements a React {@link Component} which represents the filmstrip on
 * mobile/React Native.
 *
 * @extends Component
 */
class Filmstrip extends Component<*> {
    /**
     * Filmstrip component's property types.
     *
     * @static
     */
    static propTypes = {
        /**
         * The participants in the conference.
         *
         * @private
         * @type {Participant[]}
         */
        _participants: PropTypes.array,

        /**
         * The indicator which determines whether the filmstrip is visible.
         *
         * @private
         * @type {boolean}
         */
        _visible: PropTypes.bool.isRequired
    };

    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const isNarrowAspectRatio_ = isNarrowAspectRatio(this);
        const filmstripStyle
            = isNarrowAspectRatio_
                ? styles.filmstripNarrow
                : styles.filmstripWide;

        return (
            <Container
                style = { filmstripStyle }
                visible = { this.props._visible }>
                <ScrollView
                    horizontal = { isNarrowAspectRatio_ }
                    showsHorizontalScrollIndicator = { false }
                    showsVerticalScrollIndicator = { false }>
                    {
                        /* eslint-disable react/jsx-wrap-multilines */

                        this._sort(this.props._participants)
                            .map(p =>
                                <Thumbnail
                                    key = { p.id }
                                    participant = { p } />)

                        /* eslint-enable react/jsx-wrap-multilines */
                    }
                </ScrollView>
            </Container>
        );
    }

    /**
     * Sorts a specific array of {@code Participant}s in display order.
     *
     * @param {Participant[]} participants - The array of {@code Participant}s
     * to sort in display order.
     * @private
     * @returns {Participant[]} A new array containing the elements of the
     * specified {@code participants} array sorted in display order.
     */
    _sort(participants) {
        // XXX Array.prototype.sort() is not appropriate because (1) it operates
        // in place and (2) it is not necessarily stable.

        const sortedParticipants = [];

        // Group the remote participants so that the local participant does not
        // appear in between remote participants. Have the remote participants
        // from right to left with the newest added/joined to the leftmost side.
        for (let i = participants.length - 1; i >= 0; --i) {
            const p = participants[i];

            p.local || sortedParticipants.push(p);
        }

        // Have the local participant at the rightmost side.
        for (let i = participants.length - 1; i >= 0; --i) {
            const p = participants[i];

            p.local && sortedParticipants.push(p);
        }

        return sortedParticipants;
    }
}

/**
 * Function that maps parts of Redux state tree into component props.
 *
 * @param {Object} state - Redux state.
 * @private
 * @returns {{
 *     _participants: Participant[],
 *     _visible: boolean
 * }}
 */
function _mapStateToProps(state) {
    const participants = state['features/base/participants'];

    return {
        /**
         * The participants in the conference.
         *
         * @private
         * @type {Participant[]}
         */
        _participants: participants,

        /**
         * The indicator which determines whether the filmstrip is visible. The
         * mobile/react-native Filmstrip is visible when there are at least 2
         * participants in the conference (including the local one).
         *
         * @private
         * @type {boolean}
         */
        _visible: participants.length > 1
    };
}

export default connect(_mapStateToProps)(makeAspectRatioAware(Filmstrip));
<commit_msg>[RN] Adjust filmstrip ordering based on aspect ratio<commit_after>// @flow

import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import { connect } from 'react-redux';

import {
    isNarrowAspectRatio,
    makeAspectRatioAware
} from '../../base/aspect-ratio';
import { Container } from '../../base/react';

import Thumbnail from './Thumbnail';
import { styles } from './_';

/**
 * Implements a React {@link Component} which represents the filmstrip on
 * mobile/React Native.
 *
 * @extends Component
 */
class Filmstrip extends Component<*> {
    /**
     * Filmstrip component's property types.
     *
     * @static
     */
    static propTypes = {
        /**
         * The participants in the conference.
         *
         * @private
         * @type {Participant[]}
         */
        _participants: PropTypes.array,

        /**
         * The indicator which determines whether the filmstrip is visible.
         *
         * @private
         * @type {boolean}
         */
        _visible: PropTypes.bool.isRequired
    };

    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const isNarrowAspectRatio_ = isNarrowAspectRatio(this);
        const filmstripStyle
            = isNarrowAspectRatio_
                ? styles.filmstripNarrow
                : styles.filmstripWide;
        const {
            _participants: participants,
            _visible: visible } = this.props;

        return (
            <Container
                style = { filmstripStyle }
                visible = { visible }>
                <ScrollView
                    horizontal = { isNarrowAspectRatio_ }
                    showsHorizontalScrollIndicator = { false }
                    showsVerticalScrollIndicator = { false }>
                    {
                        /* eslint-disable react/jsx-wrap-multilines */

                        this._sort(participants, isNarrowAspectRatio_)
                            .map(p =>
                                <Thumbnail
                                    key = { p.id }
                                    participant = { p } />)

                        /* eslint-enable react/jsx-wrap-multilines */
                    }
                </ScrollView>
            </Container>
        );
    }

    /**
     * Sorts a specific array of {@code Participant}s in display order.
     *
     * @param {Participant[]} participants - The array of {@code Participant}s
     * to sort in display order.
     * @param {boolean} isNarrowAspectRatio_ - Indicates if the aspect ratio is
     * wide or narrow.
     * @private
     * @returns {Participant[]} A new array containing the elements of the
     * specified {@code participants} array sorted in display order.
     */
    _sort(participants, isNarrowAspectRatio_) {
        // XXX Array.prototype.sort() is not appropriate because (1) it operates
        // in place and (2) it is not necessarily stable.

        const sortedParticipants = [

            // First put the local participant.
            ...participants.filter(p => p.local),

            // Then the remote participants, which are sorted by join order.
            ...participants.filter(p => !p.local)
        ];

        if (isNarrowAspectRatio_) {
            // When the narrow aspect ratio is used, we want to have the remote
            // participants from right to left with the newest added/joined to
            // the leftmost side. The local participant is the leftmost item.
            sortedParticipants.reverse();
        }

        return sortedParticipants;
    }
}

/**
 * Function that maps parts of Redux state tree into component props.
 *
 * @param {Object} state - Redux state.
 * @private
 * @returns {{
 *     _participants: Participant[],
 *     _visible: boolean
 * }}
 */
function _mapStateToProps(state) {
    const participants = state['features/base/participants'];

    return {
        /**
         * The participants in the conference.
         *
         * @private
         * @type {Participant[]}
         */
        _participants: participants,

        /**
         * The indicator which determines whether the filmstrip is visible. The
         * mobile/react-native Filmstrip is visible when there are at least 2
         * participants in the conference (including the local one).
         *
         * @private
         * @type {boolean}
         */
        _visible: participants.length > 1
    };
}

export default connect(_mapStateToProps)(makeAspectRatioAware(Filmstrip));
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

import APINotLoaded from 'es6!display/not_loaded';
import ChangesLinks from 'es6!display/changes/links';
import SimpleTooltip from 'es6!display/simple_tooltip';
import { AjaxError } from 'es6!display/errors';
import { ChangesChart } from 'es6!display/changes/charts';
import { Grid } from 'es6!display/grid';
import { SingleBuildStatus } from 'es6!display/changes/builds';
import { TimeText, display_duration } from 'es6!display/time';
import { get_runnable_condition } from 'es6!display/changes/build_conditions';

import InteractiveData from 'es6!pages/helpers/interactive_data';

import * as api from 'es6!server/api';

import * as utils from 'es6!utils/utils';

var CommitsTab = React.createClass({

  propTypes: {
    // the project api response. Always loaded
    project: PropTypes.object,

    // InteractiveData...makes the chart interactive and paginates
    interactive: PropTypes.object,

    // parent elem that has state
    pageElem: PropTypes.object.isRequired,
  },

  getInitialState: function() {
    // powers on-hover list of failed tests. Its ok for this to get wiped out
    // every time we switch tabs
    return { failedTests: [] };
  },

  statics: {
    getEndpoint: function(project_slug) {
      return URI(`/api/0/projects/${project_slug}/commits/`)
        .query({ 'all_builds': 1 })
        .toString();
    }
  },

  componentDidMount: function() {
    if (!this.props.interactive.hasRunInitialize()) {
      var params = this.props.isInitialTab ? InteractiveData.getParamsFromWindowUrl() : null;
      params = params || {};
      if (!params['branch']) {
        params['branch'] = this.props.project.getReturnedData()
          .repository.defaultBranch;
      }

      this.props.interactive.initialize(params || {});
    }

    // if we're revisiting this tab, let's restore the window url to the
    // current state
    if (api.isLoaded(this.props.interactive.getDataToShow())) {
      this.props.interactive.updateWindowUrl();
    }

    // TODO: maybe store this in parent state
    var repo_id = this.props.project.getReturnedData().repository.id;
    api.fetch(
      this,
      { 'branches': `/api/0/repositories/${repo_id}/branches` }
    );
  },

  render: function() {
    var interactive = this.props.interactive;

    if (interactive.hasNotLoadedInitialData()) {
      return <APINotLoaded calls={interactive.getDataToShow()} />;
    }

    // we might be in the middle of / failed to load updated data
    var error_message = null;
    if (interactive.failedToLoadUpdatedData()) {
      error_message = <AjaxError response={interactive.getDataForErrorMessage().response} />;
    }

    var style = interactive.isLoadingUpdatedData() ? {opacity: 0.5} : null;

    return

        {this.renderChart()}

      {this.renderTableControls()}
      {error_message}
      {this.renderTable()}
      {this.renderPaging()}

;
  },

  renderTableControls: function() {
    // TODO: don't do default branch logic here, since we might be showing all
    // branches. If there's no branch, add a blank option to select

    var default_branch = this.props.project.getReturnedData()
      .repository.defaultBranch;
    var current_params = this.props.interactive.getCurrentParams();
    var current_branch = current_params.branch || default_branch;

    var branch_dropdown = null;
    if (api.isError(this.state.branches) &&
        this.state.branches.getStatusCode() === '422') {

      branch_dropdown =

        <select disabled={true}>
          <option>No branches</option>
        </select>

;
    } else if (!api.isLoaded(this.state.branches)) {
      branch_dropdown =

        <select disabled={true}>
          <option value={current_branch}>{current_branch}</option>
        </select>

;
    } else {
      var options = _.chain(this.state.branches.getReturnedData())
        .pluck('name')
        .sortBy(_.identity)
        .map(n => <option value={n}>{n}</option>)
        .value();

      var onChange = evt => {
        this.props.interactive.updateWithParams(
          { branch: evt.target.value },
          true); // reset to page 0
      };

      branch_dropdown =

        <select onChange={onChange} value={current_branch}>
          {options}
        </select>

;
    }

    /*

      Showing most recent diffs since 0:00pm

      <input
        disabled={true}
        placeholder="Search by name or SHA [TODO]"
        style={{minWidth: 170, marginRight: 5}}
      />
    */
    return

      {branch_dropdown}

;
  },

  renderChart() {
    var interactive = this.props.interactive;
    var dataToShow = interactive.getDataToShow().getReturnedData();

    var builds = _.map(dataToShow, commit => {
      if (commit.builds && commit.builds.length > 0) {
        var sortedBuilds = _.sortBy(commit.builds, b => b.dateCreated).reverse();
        return _.first(sortedBuilds);
      } else {
        return {};
      }
    });

    var links = interactive.getPagingLinks({type: 'chart_paging'});
    var prevLink = interactive.hasPreviousPage() ? links[0] : '';
    var nextLink = interactive.hasNextPage() ? links[1] : '';

    return

      {prevLink}
      <ChangesChart
        type="build"
        className="inlineBlock"
        runnables={builds}
        enableLatest={!interactive.hasPreviousPage()}
      />
      {nextLink}

;
  },

  renderTable: function() {
    var data_to_show = this.props.interactive.getDataToShow().getReturnedData(),
      project_info = this.props.project.getReturnedData();

    var grid_data = _.map(data_to_show, c => this.turnIntoRow(c, project_info));

    var cellClasses = [
      'buildWidgetCell',
      'wide easyClick',
      'bluishGray nowrap',
      'bluishGray nowrap',
      'nowrap',
      'nowrap',
      'nowrap'
    ];

    var headers = [
      'Result',
      'Name',
      'Time',
      'Tests Ran',
      'Author',
      'Commit',
      'Committed'
    ];

    return <Grid
      colnum={7}
      data={grid_data}
      cellClasses={cellClasses}
      headers={headers}
    />;
  },

  turnIntoRow: function(c, project_info) {
    var title = utils.truncate(utils.first_line(c.message));
    if (c.message.indexOf("!!skipthequeue") !== -1 ||
        c.message.indexOf("#skipthequeue") !== -1) { // we used to use this

      // dropbox-specific logic: we have a commit queue (oh hey, you should
      // build one of those too)

      title =
        {title}
        <SimpleTooltip label="This commit bypassed the commit queue">

        </SimpleTooltip>
      ;
    }

    var build_widget = null, prev_builds = null, duration = null, tests = null;
    if (c.builds && c.builds.length > 0) {
      var sorted_builds = _.sortBy(c.builds, b => b.dateCreated).reverse();
      var last_build = _.first(sorted_builds);

      build_widget = <SingleBuildStatus
        build={last_build}
        parentElem={this}
      />;

      duration = get_runnable_condition(last_build) !== 'waiting' ?
        display_duration(last_build.duration / 1000) :
        null;

      tests = last_build.stats.test_count;

      title =
        {title}
      ;
    }

    // TODO: if there are any comments, show a comment icon on the right
    return [
      build_widget,
      title,
      duration,
      tests,
      ChangesLinks.author(c.author),
      ChangesLinks.phabCommit(c),
      <TimeText key={c.id} time={c.dateCommitted} />
    ];
  },

  renderPaging: function() {
    var links = this.props.interactive.getPagingLinks();
    return
{links}
;
  },
});

export default CommitsTab;
<commit_msg>Remove unused failedTests property<commit_after>import React, { PropTypes } from 'react';

import APINotLoaded from 'es6!display/not_loaded';
import ChangesLinks from 'es6!display/changes/links';
import SimpleTooltip from 'es6!display/simple_tooltip';
import { AjaxError } from 'es6!display/errors';
import { ChangesChart } from 'es6!display/changes/charts';
import { Grid } from 'es6!display/grid';
import { SingleBuildStatus } from 'es6!display/changes/builds';
import { TimeText, display_duration } from 'es6!display/time';
import { get_runnable_condition } from 'es6!display/changes/build_conditions';

import InteractiveData from 'es6!pages/helpers/interactive_data';

import * as api from 'es6!server/api';

import * as utils from 'es6!utils/utils';

var CommitsTab = React.createClass({

  propTypes: {
    // the project api response. Always loaded
    project: PropTypes.object,

    // InteractiveData...makes the chart interactive and paginates
    interactive: PropTypes.object,

    // parent elem that has state
    pageElem: PropTypes.object.isRequired,
  },

  statics: {
    getEndpoint: function(project_slug) {
      return URI(`/api/0/projects/${project_slug}/commits/`)
        .query({ 'all_builds': 1 })
        .toString();
    }
  },

  componentDidMount: function() {
    if (!this.props.interactive.hasRunInitialize()) {
      var params = this.props.isInitialTab ? InteractiveData.getParamsFromWindowUrl() : null;
      params = params || {};
      if (!params['branch']) {
        params['branch'] = this.props.project.getReturnedData()
          .repository.defaultBranch;
      }

      this.props.interactive.initialize(params || {});
    }

    // if we're revisiting this tab, let's restore the window url to the
    // current state
    if (api.isLoaded(this.props.interactive.getDataToShow())) {
      this.props.interactive.updateWindowUrl();
    }

    // TODO: maybe store this in parent state
    var repo_id = this.props.project.getReturnedData().repository.id;
    api.fetch(
      this,
      { 'branches': `/api/0/repositories/${repo_id}/branches` }
    );
  },

  render: function() {
    var interactive = this.props.interactive;

    if (interactive.hasNotLoadedInitialData()) {
      return <APINotLoaded calls={interactive.getDataToShow()} />;
    }

    // we might be in the middle of / failed to load updated data
    var error_message = null;
    if (interactive.failedToLoadUpdatedData()) {
      error_message = <AjaxError response={interactive.getDataForErrorMessage().response} />;
    }

    var style = interactive.isLoadingUpdatedData() ? {opacity: 0.5} : null;

    return

        {this.renderChart()}

      {this.renderTableControls()}
      {error_message}
      {this.renderTable()}
      {this.renderPaging()}

;
  },

  renderTableControls: function() {
    // TODO: don't do default branch logic here, since we might be showing all
    // branches. If there's no branch, add a blank option to select

    var default_branch = this.props.project.getReturnedData()
      .repository.defaultBranch;
    var current_params = this.props.interactive.getCurrentParams();
    var current_branch = current_params.branch || default_branch;

    var branch_dropdown = null;
    if (api.isError(this.state.branches) &&
        this.state.branches.getStatusCode() === '422') {

      branch_dropdown =

        <select disabled={true}>
          <option>No branches</option>
        </select>

;
    } else if (!api.isLoaded(this.state.branches)) {
      branch_dropdown =

        <select disabled={true}>
          <option value={current_branch}>{current_branch}</option>
        </select>

;
    } else {
      var options = _.chain(this.state.branches.getReturnedData())
        .pluck('name')
        .sortBy(_.identity)
        .map(n => <option value={n}>{n}</option>)
        .value();

      var onChange = evt => {
        this.props.interactive.updateWithParams(
          { branch: evt.target.value },
          true); // reset to page 0
      };

      branch_dropdown =

        <select onChange={onChange} value={current_branch}>
          {options}
        </select>

;
    }

    /*

      Showing most recent diffs since 0:00pm

      <input
        disabled={true}
        placeholder="Search by name or SHA [TODO]"
        style={{minWidth: 170, marginRight: 5}}
      />
    */
    return

      {branch_dropdown}

;
  },

  renderChart() {
    var interactive = this.props.interactive;
    var dataToShow = interactive.getDataToShow().getReturnedData();

    var builds = _.map(dataToShow, commit => {
      if (commit.builds && commit.builds.length > 0) {
        var sortedBuilds = _.sortBy(commit.builds, b => b.dateCreated).reverse();
        return _.first(sortedBuilds);
      } else {
        return {};
      }
    });

    var links = interactive.getPagingLinks({type: 'chart_paging'});
    var prevLink = interactive.hasPreviousPage() ? links[0] : '';
    var nextLink = interactive.hasNextPage() ? links[1] : '';

    return

      {prevLink}
      <ChangesChart
        type="build"
        className="inlineBlock"
        runnables={builds}
        enableLatest={!interactive.hasPreviousPage()}
      />
      {nextLink}

;
  },

  renderTable: function() {
    var data_to_show = this.props.interactive.getDataToShow().getReturnedData(),
      project_info = this.props.project.getReturnedData();

    var grid_data = _.map(data_to_show, c => this.turnIntoRow(c, project_info));

    var cellClasses = [
      'buildWidgetCell',
      'wide easyClick',
      'bluishGray nowrap',
      'bluishGray nowrap',
      'nowrap',
      'nowrap',
      'nowrap'
    ];

    var headers = [
      'Result',
      'Name',
      'Time',
      'Tests Ran',
      'Author',
      'Commit',
      'Committed'
    ];

    return <Grid
      colnum={7}
      data={grid_data}
      cellClasses={cellClasses}
      headers={headers}
    />;
  },

  turnIntoRow: function(c, project_info) {
    var title = utils.truncate(utils.first_line(c.message));
    if (c.message.indexOf("!!skipthequeue") !== -1 ||
        c.message.indexOf("#skipthequeue") !== -1) { // we used to use this

      // dropbox-specific logic: we have a commit queue (oh hey, you should
      // build one of those too)

      title =
        {title}
        <SimpleTooltip label="This commit bypassed the commit queue">

        </SimpleTooltip>
      ;
    }

    var build_widget = null, prev_builds = null, duration = null, tests = null;
    if (c.builds && c.builds.length > 0) {
      var sorted_builds = _.sortBy(c.builds, b => b.dateCreated).reverse();
      var last_build = _.first(sorted_builds);

      build_widget = <SingleBuildStatus
        build={last_build}
        parentElem={this}
      />;

      duration = get_runnable_condition(last_build) !== 'waiting' ?
        display_duration(last_build.duration / 1000) :
        null;

      tests = last_build.stats.test_count;

      title =
        {title}
      ;
    }

    // TODO: if there are any comments, show a comment icon on the right
    return [
      build_widget,
      title,
      duration,
      tests,
      ChangesLinks.author(c.author),
      ChangesLinks.phabCommit(c),
      <TimeText key={c.id} time={c.dateCommitted} />
    ];
  },

  renderPaging: function() {
    var links = this.props.interactive.getPagingLinks();
    return
{links}
;
  },
});

export default CommitsTab;
<|endoftext|>


<commit_before>var $projectForm = $('#projectForm');

$projectForm.on('submit', function (e) {
    e.preventDefault();
    var data = new FormData(this);
    $.ajax({
        method: "POST",
        url: "/addProject",
        contentType: false,
        processData: false,
        data: data
    }).done(function (msg) {
        drawProjectList();
    }).fail(function (msg) {
        alert(msg.responseText);
    });
});

var $projectList = $('#projectList');
var projectListCache = [];

var fuse = new Fuse(projectListCache, { keys: ['name'] });

var str = '
' +
            '
'+
                '
%name%
' +
                '%data% 更新' +
                '
%description%
' +
            '
' +
            '
' +
            '
' +
        '
';

function drawProjectList() {
    $.ajax({
        method: "POST",
        url: "/listProject"
    }).done(function (msg) {
        var html = '';
        if (msg.length > 0) {
            projectListCache = msg;
            fuse = new Fuse(projectListCache, { keys: ['name'] });
            msg.forEach(function (o, i) {
                // console.log(o);

                var t = str.replace(/(%(\w+)%)/g,function($1,$2,$3){
                    return o[$3] ? o[$3] : '';
                });
                html += t;
            });

            $projectList.html(html);
        }
    }).fail(function (msg) {
        alert(msg);
    });
}

drawProjectList();

var headerHeight = $('header').height();

$(window).on('scroll',function(e){
    var _top = $(this).scrollTop();

    // 假如超过高度就悬浮
    if(_top >= headerHeight){
        // $('.searchPlaceholder').addClass('fixed');
    }else{
        // $('.searchPlaceholder').removeClass('fixed');
        var scale = (2-_top/headerHeight)/2;
        $('header').css({
            '-webkit-transform' : 'scale3d('+scale+','+scale+',1)',
            'transform' : 'scale3d('+scale+','+scale+',1)'
        })
    }

})

var $searchField = $('#searchField');

$searchField.on('input', function () {
    // var $me = $(this);
    var key  = $(this).val();
    var data = fuse.search(key);
    var html = '';
    if (data.length > 0) {
        data.forEach(function (o, i) {
            var t = str.replace(/(%(\w+)%)/g,function($1,$2,$3){
                return o[$3] ? o[$3] : '';
            });
            html += t;
        });
    }
    $projectList.html(html);
});
<commit_msg>搜索逻辑加入<commit_after>var $projectForm = $('#projectForm');

$projectForm.on('submit', function (e) {
    e.preventDefault();
    var data = new FormData(this);
    $.ajax({
        method: "POST",
        url: "/addProject",
        contentType: false,
        processData: false,
        data: data
    }).done(function (msg) {
        drawProjectList();
    }).fail(function (msg) {
        alert(msg.responseText);
    });
});

var $projectList = $('#projectList');
var projectListCache = [];

var fuse = new Fuse(projectListCache, { keys: ['name'] });

var str = '
' +
            '
'+
                '
%name%
' +
                '%data% 更新' +
                '
%description%
' +
            '
' +
            '
' +
            '
' +
        '
';

function drawProjectList() {
    $.ajax({
        method: "POST",
        url: "/listProject"
    }).done(function (msg) {
        var html = '';
        if (msg.length > 0) {
            projectListCache = msg;
            fuse = new Fuse(projectListCache, { keys: ['name'] });
            msg.forEach(function (o, i) {
                // console.log(o);

                var t = str.replace(/(%(\w+)%)/g,function($1,$2,$3){
                    return o[$3] ? o[$3] : '';
                });
                html += t;
            });

            $projectList.html(html);
        }
    }).fail(function (msg) {
        alert(msg);
    });
}

drawProjectList();

var headerHeight = $('header').height();

$(window).on('scroll',function(e){
    var _top = $(this).scrollTop();

    // 假如超过高度就悬浮
    if(_top >= headerHeight){
        // $('.searchPlaceholder').addClass('fixed');
    }else{
        // $('.searchPlaceholder').removeClass('fixed');
        var scale = (2-_top/headerHeight)/2;
        $('header').css({
            '-webkit-transform' : 'scale3d('+scale+','+scale+',1)',
            'transform' : 'scale3d('+scale+','+scale+',1)'
        })
    }

})

var $searchField = $('#searchField');

$searchField.on('input', function () {
    // var $me = $(this);
    var key  = $(this).val();
    var data = fuse.search(key);
    var html = '';
    if (data.length > 0) {
        data.forEach(function (o, i) {
            var t = str.replace(/(%(\w+)%)/g,function($1,$2,$3){
                return o[$3] ? o[$3] : '';
            });
            html += t;
        });
    }else{
        projectListCache.forEach(function (o, i) {
            var t = str.replace(/(%(\w+)%)/g,function($1,$2,$3){
                return o[$3] ? o[$3] : '';
            });
            html += t;
        });
    }
    $projectList.html(html);
});
<|endoftext|>


<commit_before>import { Component } from 'angular2/core';

@Component({
  selector: 'contact-app',
  template: '
Hi There!
'
})
class AppComponent {
}

export default AppComponent;
<commit_msg>Added multiple components<commit_after>import { Component } from 'angular2/core';
import { HTTP_PROVIDERS } from 'angular2/http';
import ContactList from './ContactList.js';

@Component({
  selector: 'contact-app',
  providers: [HTTP_PROVIDERS],
  template: `

{{ title }}

    <contact-list></contact-list>

  `,
  directives: [ContactList]
})
class AppComponent {
  constructor() {
    this.title = 'Hello World';
  }
}

export default AppComponent;
<|endoftext|>


<commit_before>/* global */

// Create an 'App' namespace if it doesn't already exist
var App = App || {};

/**
 * Base module
 *
 * Modified: YYYY/MM/DD
 * @author author
 */
App.base = (function ($, window, document, undefined) {
    // Constants

    // SemVer version number of the module
    var VERSION = '1.0.0';

    // Unique global identifier. Internal usage only
    // var GUID = 'EBF09F7D-008B-4B56-8227-0B5378649968';

    // Fields

    // Methods

    /**
     * Initialisation function
     *
     * @return {undefined}
     */
    function init(config) {
        // Default config that can be overwritten by passing through the config variable
        var defaultConfig = {};

        // Combine the passed config
        $.extend(defaultConfig, config);

        cacheDom();
    }

    /**
     * Get the version number of the module
     *
     * @returns {number} Version number
     */
    function getVersion() {
        return VERSION;
    }

    /**
     * Initialise all DOM cachable variables
     *
     * @return {undefined}
     */
    function cacheDom() {}

    // Invoked when the DOM has loaded
    $(function () {
        init({});
    });

    // Public API
    return {
        getVersion: getVersion
    };
})(jQuery, window, document);
<commit_msg>Updated base module<commit_after>/* global App */

// Create an 'App' namespace if it doesn't already exist
App = App || {};

/**
 * Base module
 *
 * Modified: YYYY/MM/DD
 * @author author
 */
App.base = (function ($, window, document, undefined) {
    // Constants

    // SemVer version number of the module
    var VERSION = '1.0.0';

    // Unique global identifier. Internal usage only
    // var GUID = '27AB85AB-3AD5-42C6-A086-30FF65668693';

    // Fields

    // Methods

    /**
     * Initialisation function
     *
     * @return {undefined}
     */
    function init(config) {
        // Default config that can be overwritten by passing through the config variable
        var defaultConfig = {};

        // Combine the passed config
        $.extend(defaultConfig, config);

        _cacheDom();
    }

    /**
     * Destroy the module
     *
     * @return {undefined}
     */
    function destroy() {}

    /**
     * Get the version number of the module
     *
     * @returns {number} Version number
     */
    function getVersion() {
        return VERSION;
    }

    /**
     * Initialise all DOM cachable variables
     *
     * @return {undefined}
     */
    function _cacheDom() {}

    // Invoked when the DOM has loaded
    $(function () {
        // init({});
    });

    // Public API
    return {
        init: init,
        destroy: destroy,
        getVersion: getVersion
    };
})(jQuery, window, document);
<|endoftext|>


<commit_before>function inArray(name, ao) {
  for (var i = 0; i < ao.length; i += 1) {
    if (ao[i]['name'] == name) {
      return true;
    }
  }
  return false;
}

function initTable(oTable) {
  $.ajax({
    url: '/users/json',
    type: 'GET',
    dataType: 'json'
  }).done(function (json) {
    oTable.fnClearTable();
    oTable.fnAddData(json);
    oTable.fnDraw();
  }).fail(function (jqXHR, status, error) {
    $('#message').append('
<button class="close" data-dismiss="alert">x</button>Cannot reach the server for users information.
');
  }).always();
}

function updateFromModal(cb) {
  $('#remove').prop('disabled', true);
  var number = $('#modal .modal-body div').length;
  $('#modal .modal-body div').each(function (index) {
    var that = this;
    $.ajax({
      url: '/users/' + that.id + '/refresh',
      type: 'GET'
    }).done(function () {
      $(that).prepend('');
      $(that).addClass('text-success');
    })
      .fail(function (jqXHR, status, error) {
        $(that).append(' : ' + jqXHR.responseText);
        $(that).addClass('text-error');
      })
      .always(function () {
        number = number - 1;
        if (number === 0) {
          if (cb) {
            cb();
          }
        }
      });
  });
}

function modifyFromModal(cb) {
  $('#remove').prop('disabled', true);
  var number = $('#modal .modal-body div').length;
  var roles = [];
  $('#modal-roles input:checked').each(function() {
      roles.push($(this).val());
    });
  $('#modal .modal-body div').each(function (index) {
    var that = this;
    $.ajax({
      url: '/users/' + that.id,
      type: 'PUT',
      contentType: 'application/json',
      data: JSON.stringify({
        roles:roles
      }),
    }).done(function () {
      $(that).prepend('');
      $(that).addClass('text-success');
    })
      .fail(function (jqXHR, status, error) {
        $(that).append(' : ' + jqXHR.responseText);
        $(that).addClass('text-error');
      })
      .always(function () {
        number = number - 1;
        if (number === 0) {
          if (cb) {
            cb();
          }
        }
      });
  });
}

$(function () {
  $('#username').typeahead({
    name: 'usernames',
    limit: 20,
    valueKey: 'displayName',
    prefetch: '/adusernames'
  });

  var userTable = $('#users').dataTable({
    aaData: [],
    // bAutoWidth: false,
    aoColumns: [selectColumn, useridColumn, fullNameNoLinkColumn, rolesColumn, lastVisitedOnColumn],
    aaSorting: [
      [4, 'desc'],
      [1, 'asc']
    ],
    sDom: sDom,
    oTableTools: oTableTools
  });
  selectEvent();
  filterEvent();

  $('#add').click(function (e) {
    e.preventDefault();
    var name = $('#username').val();
    if (inArray(name, userTable.fnGetData())) {
      //show message
      $('#message').append('
<button class="close" data-dismiss="alert">x</button>The user named ' + name + ' is already in the user list.
');
    } else {
      $.ajax({
        url: '/users/',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
          name: name,
          manager: $('#manager').prop('checked'),
          admin: $('#admin').prop('checked')
        }),
        success: function (data, status, jqXHR) {
          $('#message').append('
<button class="close" data-dismiss="alert">x</button>' + jqXHR.responseText + '
');
          initTable(userTable);
        },
        error: function (jqXHR, status, error) {
          $('#message').append('
<button class="close" data-dismiss="alert">x</button>Cannot update the share list : ' + jqXHR.responseText + '
');
        }
      });
    }
    document.forms[0].reset();
  });

  $('#user-update').click(function (e) {
    var selected = fnGetSelected(userTable, 'row-selected');
    if (selected.length) {
      $('#modalLabel').html('Update the following ' + selected.length + ' users from the application? ');
      $('#modal .modal-body').empty();
      selected.forEach(function (row) {
        var data = userTable.fnGetData(row);
        $('#modal .modal-body').append('
' + data.name + '
');
      });
      $('#modal .modal-footer').html('<button id="update" class="btn btn-primary">Confirm</button><button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#update').click(function (e) {
        e.preventDefault();
        $('#update').prop('disabled', true);
        updateFromModal(function () {
          initTable(userTable);
        });
      });
      $('#modal').modal('show');
    } else {
      $('#modalLabel').html('Alert');
      $('#modal .modal-body').html('No users has been selected!');
      $('#modal .modal-footer').html('<button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#modal').modal('show');
    }
  });

  $('#user-modify').click(function (e) {
    var selected = fnGetSelected(userTable, 'row-selected');
    if (selected.length) {
      $('#modalLabel').html('Modify the following ' + selected.length + ' users\' role? ');
      $('#modal .modal-body').empty();
      $('#modal .modal-body').append('<form id="modal-roles" class="form-inline"><input id="modal-manager" type="checkbox" value="manager">manager <input id="modal-admin" type="checkbox" value="admin">admin </form>');
      selected.forEach(function (row) {
        var data = userTable.fnGetData(row);
        $('#modal .modal-body').append('
' + data.name + '
');
      });
      $('#modal .modal-footer').html('<button id="modify" class="btn btn-primary">Confirm</button><button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#modify').click(function (e) {
        e.preventDefault();
        $('#modify').prop('disabled', true);
        modifyFromModal(function () {
          initTable(userTable);
        });
      });
      $('#modal').modal('show');
    } else {
      $('#modalLabel').html('Alert');
      $('#modal .modal-body').html('No users has been selected!');
      $('#modal .modal-footer').html('<button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#modal').modal('show');
    }
  });

  initTable(userTable);
});
<commit_msg>call ajax prefix and jslint<commit_after>/*global selectColumn: false, useridColumn: false, fullNameNoLinkColumn: false, rolesColumn: false, lastVisitedOnColumn: false, fnGetSelected: false, selectEvent: false, filterEvent: false, sDom: false, oTableTools: false*/
/*global updateAjaxURL: false, prefix: false*/

function inArray(name, ao) {
  var i;
  for (i = 0; i < ao.length; i += 1) {
    if (ao[i].name === name) {
      return true;
    }
  }
  return false;
}

function initTable(oTable) {
  $.ajax({
    url: '/users/json',
    type: 'GET',
    dataType: 'json'
  }).done(function (json) {
    oTable.fnClearTable();
    oTable.fnAddData(json);
    oTable.fnDraw();
  }).fail(function (jqXHR, status, error) {
    $('#message').append('
<button class="close" data-dismiss="alert">x</button>Cannot reach the server for users information.
');
  }).always();
}

function updateFromModal(cb) {
  $('#remove').prop('disabled', true);
  var number = $('#modal .modal-body div').length;
  $('#modal .modal-body div').each(function (index) {
    var that = this;
    $.ajax({
      url: '/users/' + that.id + '/refresh',
      type: 'GET'
    }).done(function () {
      $(that).prepend('');
      $(that).addClass('text-success');
    }).fail(function (jqXHR, status, error) {
      $(that).append(' : ' + jqXHR.responseText);
      $(that).addClass('text-error');
    }).always(function () {
      number = number - 1;
      if (number === 0) {
        if (cb) {
          cb();
        }
      }
    });
  });
}

function modifyFromModal(cb) {
  $('#remove').prop('disabled', true);
  var number = $('#modal .modal-body div').length;
  var roles = [];
  $('#modal-roles input:checked').each(function () {
    roles.push($(this).val());
  });
  $('#modal .modal-body div').each(function (index) {
    var that = this;
    $.ajax({
      url: '/users/' + that.id,
      type: 'PUT',
      contentType: 'application/json',
      data: JSON.stringify({
        roles: roles
      })
    }).done(function () {
      $(that).prepend('');
      $(that).addClass('text-success');
    }).fail(function (jqXHR, status, error) {
      $(that).append(' : ' + jqXHR.responseText);
      $(that).addClass('text-error');
    }).always(function () {
      number = number - 1;
      if (number === 0) {
        if (cb) {
          cb();
        }
      }
    });
  });
}

$(function () {
  updateAjaxURL(prefix);

  $('#username').typeahead({
    name: 'usernames',
    limit: 20,
    valueKey: 'displayName',
    prefetch: '/adusernames'
  });

  var userTable = $('#users').dataTable({
    aaData: [],
    // bAutoWidth: false,
    aoColumns: [selectColumn, useridColumn, fullNameNoLinkColumn, rolesColumn, lastVisitedOnColumn],
    aaSorting: [
      [4, 'desc'],
      [1, 'asc']
    ],
    sDom: sDom,
    oTableTools: oTableTools
  });
  selectEvent();
  filterEvent();

  $('#add').click(function (e) {
    e.preventDefault();
    var name = $('#username').val();
    if (inArray(name, userTable.fnGetData())) {
      //show message
      $('#message').append('
<button class="close" data-dismiss="alert">x</button>The user named ' + name + ' is already in the user list.
');
    } else {
      $.ajax({
        url: '/users/',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
          name: name,
          manager: $('#manager').prop('checked'),
          admin: $('#admin').prop('checked')
        }),
        success: function (data, status, jqXHR) {
          $('#message').append('
<button class="close" data-dismiss="alert">x</button>' + jqXHR.responseText + '
');
          initTable(userTable);
        },
        error: function (jqXHR, status, error) {
          $('#message').append('
<button class="close" data-dismiss="alert">x</button>Cannot update the share list : ' + jqXHR.responseText + '
');
        }
      });
    }
    document.forms[0].reset();
  });

  $('#user-update').click(function (e) {
    var selected = fnGetSelected(userTable, 'row-selected');
    if (selected.length) {
      $('#modalLabel').html('Update the following ' + selected.length + ' users from the application? ');
      $('#modal .modal-body').empty();
      selected.forEach(function (row) {
        var data = userTable.fnGetData(row);
        $('#modal .modal-body').append('
' + data.name + '
');
      });
      $('#modal .modal-footer').html('<button id="update" class="btn btn-primary">Confirm</button><button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#update').click(function (e) {
        e.preventDefault();
        $('#update').prop('disabled', true);
        updateFromModal(function () {
          initTable(userTable);
        });
      });
      $('#modal').modal('show');
    } else {
      $('#modalLabel').html('Alert');
      $('#modal .modal-body').html('No users has been selected!');
      $('#modal .modal-footer').html('<button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#modal').modal('show');
    }
  });

  $('#user-modify').click(function (e) {
    var selected = fnGetSelected(userTable, 'row-selected');
    if (selected.length) {
      $('#modalLabel').html('Modify the following ' + selected.length + ' users\' role? ');
      $('#modal .modal-body').empty();
      $('#modal .modal-body').append('<form id="modal-roles" class="form-inline"><input id="modal-manager" type="checkbox" value="manager">manager <input id="modal-admin" type="checkbox" value="admin">admin </form>');
      selected.forEach(function (row) {
        var data = userTable.fnGetData(row);
        $('#modal .modal-body').append('
' + data.name + '
');
      });
      $('#modal .modal-footer').html('<button id="modify" class="btn btn-primary">Confirm</button><button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#modify').click(function (e) {
        e.preventDefault();
        $('#modify').prop('disabled', true);
        modifyFromModal(function () {
          initTable(userTable);
        });
      });
      $('#modal').modal('show');
    } else {
      $('#modalLabel').html('Alert');
      $('#modal .modal-body').html('No users has been selected!');
      $('#modal .modal-footer').html('<button data-dismiss="modal" aria-hidden="true" class="btn">Return</button>');
      $('#modal').modal('show');
    }
  });

  initTable(userTable);
});
<|endoftext|>


<commit_before>/*global describe, it, browser, require */

describe('toast', function () {
    'use strict';

    it('should match the baseline toast default screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open')
            .waitForVisible('#toast-container');

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast info screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-info')
            .waitForVisible('#toast-container');

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_info',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast success screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-success')
            .waitForVisible('#toast-container');

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_success',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast warning screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-warning')
            .waitForVisible('#toast-container');

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_warning',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast danger screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-danger')
            .waitForVisible('#toast-container');

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_danger',
            selector: '#toast-container',
            done: done
        });
    });
});
<commit_msg>use 1500ms timeout for toast waitforvisible<commit_after>/*global describe, it, browser, require */

describe('toast', function () {
    'use strict';

    it('should match the baseline toast default screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open')
            .waitForVisible('#toast-container', 1500);

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast info screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-info')
            .waitForVisible('#toast-container', 1500);

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_info',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast success screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-success')
            .waitForVisible('#toast-container', 1500);

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_success',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast warning screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-warning')
            .waitForVisible('#toast-container', 1500);

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_warning',
            selector: '#toast-container',
            done: done
        });
    });

    it('should match the baseline toast danger screenshot', function (done) {
        var result,
            common = require('../common');

        result = browser.url('/toast/fixtures/test.full.html')
            .click('#screenshot-toast-open-danger')
            .waitForVisible('#toast-container', 1500);

        common.compareScreenshot({
            browserResult: result,
            prefix: common.getPrefix(browser),
            screenshotName: 'toast_danger',
            selector: '#toast-container',
            done: done
        });
    });
});
<|endoftext|>


<commit_before>var express = require("express");
var router = express.Router();
var Q = require('q');
var crypto = require('crypto');
var uuid = require('node-uuid');

router.route('/').get(function(req,res){

    console.log("Started looking up locations.");
    var db = require("../imp_services/impdb.js").connect();
    Q.fcall(db.beginTransaction())
        .then(db.query("USE " + db.databaseName))
        .then(db.query("CALL GetInventoryLocations();"))
        .then(function(row) {

            // We got data about the user
            if (row[0][0].length == 0) { // No user by that username
                res.end("Invalid Credentials!");
            }
            else {
                var locations = [];
                for (var i = 0; i < row[0][0].length; i++)
                {
                    locations.push(row[0][0][i].location);
                }

                var sendLocations = {"locationList" : locations};
                    res.send(JSON.stringify(sendLocations));
                res.end(JSON.stringify(sendLocations));
                }
            })
        .then(db.commit())
        .then(db.endTransaction())
        .catch(function(err){
            Q.fcall(db.rollback())
                .then(db.endTransaction())
                .then(console.log("We had an error") )
                .done();
            console.log("Error: " + err);
            res.status(503).send("ERROR: " + err);
        })
        .done();

});

module.exports = router;
<commit_msg>Locations complete<commit_after>var express = require("express");
var router = express.Router();
var Q = require('q');
var crypto = require('crypto');
var uuid = require('node-uuid');

router.route('/:productID').get(function(req,res){

    var productID = req.params.productID;
    console.log("Started looking up locations.");
    var db = require("../imp_services/impdb.js").connect();
    Q.fcall(db.beginTransaction())
        .then(db.query("USE " + db.databaseName))
        .then(db.query("CALL GetInventoryLocations(" + productID +");"))
        .then(function(row) {

            // We got data about the user
            if (row[0][0].length == 0) { // No user by that username
                res.end("Invalid Credentials!");
            }
            else {
                var locations = [];
                for (var i = 0; i < row[0][0].length; i++)
                {
                   // console.log(row[0][0][i].Location);
                    locations.push(row[0][0][i].Location);
                }

                var sendLocations = {"locationList" : locations};
                    res.send(JSON.stringify(sendLocations));
                res.end(JSON.stringify(sendLocations));
                }
            })
        .then(db.commit())
        .then(db.endTransaction())
        .catch(function(err){
            Q.fcall(db.rollback())
                .then(db.endTransaction())
                .then(console.log("We had an error") )
                .done();
            console.log("Error: " + err);
            res.status(503).send("ERROR: " + err);
        })
        .done();

});

module.exports = router;
<|endoftext|>


<commit_before>import React from 'react'
import {connect} from 'react-redux';
import RouteMethod from './route';
import {Link} from 'react-router';
import GitHubButton from 'react-github-button';

import {Navbar, Nav, NavItem} from 'react-bootstrap';

export function App({user, children}) {
  return

    <MainNav user={user} transparent={children.type.transparentNavBar} />

{children}

}

export function MainNav({user, transparent}) {
  return <Navbar className={transparent ? "navbar-inverse" : null}>
    <Navbar.Header>
      <Link to="/">
        {
          transparent ?
          :

        }
      </Link>
      <Navbar.Toggle />
    </Navbar.Header>
    <Navbar.Collapse>

        <NavItem eventKey={2} href="#/pricing">Pricing</NavItem>
        {user && user._auth ? <NavItem eventKey={2} href="#/links">Links</NavItem> : null}
        {user && user._auth ? <NavItem eventKey={3} href="#/settings">Settings</NavItem> : null}

      <UserNav user={user} transparent={transparent} />
    </Navbar.Collapse>
  </Navbar>;
}

export function Index() {
  return

A pipeline for changes

          With Backstroke, always keep your repository's forks up to date.

          Open source maintainers can merge contributor's code with one click.

          Contributors don't have to worry about hefty merge conflicts.

        {/* <GitHubButton type="stargazers" size="large" namespace="1egoman" repo="backstroke" /> */}

            Sign in with Github

              To the README

        Used by

;
}
Index.transparentNavBar = true;

export function Pricing() {
  return

Pricing

              Free
              Use for free

Sync changes from upstream to forks

Sync changes between two repositories

Sync between arbitrary branches of each repository

Changes are proposed as pull requests

Use for free

              Sign up

              Premium
              $1.00 per premium link per month

Sync changes from upstream to forks

Sync changes between two repositories

Sync between arbitrary branches of each repository

Changes are proposed as pull requests

                Premium
                Sync changes to private repositories on Github

                Premium
                Premium support

                Premium
                Less than the price of a lunch per year

$1.00 per premium link per month

              Sign up for Premium

;
}

function UserNav({user, transparent}) {
  // Login status
  if (user && user._auth) {
    return
      <NavItem eventKey={2} href="/logout" className="user-nav">

        Logout {user.user}
      </NavItem>
    ;
  } else if (!transparent) {
    return <Navbar.Form pullRight>
      Login with Github
    </Navbar.Form>;
  } else {
    return null;
  }
}

export default connect((state, props) => {
  return {user: state.user, children: props.children};
}, dispatch => new Object)(App)
<commit_msg>code: remove cachet for now as I don't have express approval<commit_after>import React from 'react'
import {connect} from 'react-redux';
import RouteMethod from './route';
import {Link} from 'react-router';
import GitHubButton from 'react-github-button';

import {Navbar, Nav, NavItem} from 'react-bootstrap';

export function App({user, children}) {
  return

    <MainNav user={user} transparent={children.type.transparentNavBar} />

{children}

}

export function MainNav({user, transparent}) {
  return <Navbar className={transparent ? "navbar-inverse" : null}>
    <Navbar.Header>
      <Link to="/">
        {
          transparent ?
          :

        }
      </Link>
      <Navbar.Toggle />
    </Navbar.Header>
    <Navbar.Collapse>

        <NavItem eventKey={2} href="#/pricing">Pricing</NavItem>
        {user && user._auth ? <NavItem eventKey={2} href="#/links">Links</NavItem> : null}
        {user && user._auth ? <NavItem eventKey={3} href="#/settings">Settings</NavItem> : null}

      <UserNav user={user} transparent={transparent} />
    </Navbar.Collapse>
  </Navbar>;
}

export function Index() {
  return

A pipeline for changes

          With Backstroke, always keep your repository's forks up to date.

          Open source maintainers can merge contributor's code with one click.

          Contributors don't have to worry about hefty merge conflicts.

        {/* <GitHubButton type="stargazers" size="large" namespace="1egoman" repo="backstroke" /> */}

            Sign in with Github

              To the README

        Used by

        {/**/}

;
}
Index.transparentNavBar = true;

export function Pricing() {
  return

Pricing

              Free
              Use for free

Sync changes from upstream to forks

Sync changes between two repositories

Sync between arbitrary branches of each repository

Changes are proposed as pull requests

Use for free

              Sign up

              Premium
              $1.00 per premium link per month

Sync changes from upstream to forks

Sync changes between two repositories

Sync between arbitrary branches of each repository

Changes are proposed as pull requests

                Premium
                Sync changes to private repositories on Github

                Premium
                Premium support

                Premium
                Less than the price of a lunch per year

$1.00 per premium link per month

              Sign up for Premium

;
}

function UserNav({user, transparent}) {
  // Login status
  if (user && user._auth) {
    return
      <NavItem eventKey={2} href="/logout" className="user-nav">

        Logout {user.user}
      </NavItem>
    ;
  } else if (!transparent) {
    return <Navbar.Form pullRight>
      Login with Github
    </Navbar.Form>;
  } else {
    return null;
  }
}

export default connect((state, props) => {
  return {user: state.user, children: props.children};
}, dispatch => new Object)(App)
<|endoftext|>


<commit_before>'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = mongoose.Types.ObjectId;

const timer = require('../../../lib/timer');

const PlayerScheme = new Schema({
  id: { type: Schema.Types.ObjectId },
  name: { type: String, default: 'Ms. Anonymous'},
  x: { type: Number, },
  y: { type: Number, },
  _nextMove: {
    x: { type: Number, },
    y: { type: Number, },
  },
}, { _id : false });

const GoalSchema = new Schema({
  x: { type: Number, },
  y: { type: Number, },
  is_achieved: { type: Boolean, }
}, { _id : false });

let BoardSchema = new Schema({
  board: {
    width: { type: Number, default: 40, },
    height: { type: Number, default: 40, },
  },
  round: { type: Number, default: 0, },
  players: [PlayerScheme],
  numOfPlayers: { type: Number, default: 0, },
  goals: [GoalSchema],
  origin: {
    x: { type: Number, default: 5 },
    y: { type: Number, default: 5 },
  },
  status: {
    type: String, default: 'ongoing', enum: ['ongoing', 'lose', 'win'],
  },
  _nextRoundDeadline: { type: Date, required: true, },
});

/**
 * @returns Promise
 */
BoardSchema.statics.createBoardWithOnePlayer = function(playerIdHexString, playerName) {
  let boardId = new ObjectId();
  let playerId = new ObjectId(playerIdHexString);

  return this.create({
    _id: boardId,
    board: {
      width: 40,
      height: 40
    },
    players: [{
      id: playerId,
      name: playerName,
      x: 5,
      y: 5
    }],
    numOfPlayers: 1,
    goals: [{
      x: 10,
      y: 20,
      is_achieved: false
    }],
    _nextRoundDeadline: timer.nextTenSeconds(new Date())
  })
  .then(() => (boardId.toString()));
};

/**
 * @returns Promise
 */
BoardSchema.statics.findAvailableBoard = function() {
  return this.findOne({
    numOfPlayers: {
      $lt: 30000
    },
    status: 'ongoing'
  })
  .then((board) => {
    if (board)
      return board._id.toString();
    else
      return null;
  });
};

BoardSchema.statics.insertNewPlayer = function(boardIdHexString, playerIdHexString, playerName) {
  let boardId = new ObjectId(boardIdHexString);
  let playerId = new ObjectId(playerIdHexString);
  return this.update({
    _id: boardId
  }, {
    $push: {
      players: {
        id: playerId,
        name: playerName,
        x: 5,
        y: 5
      }
    },
    $inc: {
      numOfPlayers: 1
    }
  });
};

/**
 * @param {string} boardIdHexString
 * @param {string} playerIdHexString
 * @param {number} nextRound
 * @param {number} nextX
 * @param {number} nextY
 */
BoardSchema.statics.updateNextMove = function(boardIdHexString, playerIdHexString,
  nextRound, nextX, nextY) {
  let boardId = new ObjectId(boardIdHexString);
  let playerId = new ObjectId(playerIdHexString);

  return this.update({
    _id: boardId,
    'players.id': playerId,
    round: nextRound,
  }, {
    $set: {
      'players.$._nextMove': {
        x: nextX,
        y: nextY,
      }
    },
  });
};

BoardSchema.statics.removePlayer = function(boardIdHexString, playerIdHexString) {
  let boardId = new ObjectId(boardIdHexString);
  let playerId = new ObjectId(playerIdHexString);

  return this.update({
    _id: boardId,
    'players.id': playerId,
  }, {
    $unset: {
      'players.$': '',
    },
    $inc: {
      numOfPlayers: -1,
    }
  });
};

BoardSchema.methods.toTidyObject = function() {
  let result = this.toObject();
  result.id = result._id.toString();
  delete result._id;
  if ('__v' in result)
    delete result.__v;
  result.players = result.players
  .filter((player) => (player))
  .map((player) => ({
    id: player.id,
    name: player.name,
    x: player.x,
    y: player.y
  }));
  return result;
};

BoardSchema.methods.nextRound = function(players, status) {
  return this.update({
    $set: {
      players: players,
      status: status,
      _nextRoundDeadline: timer.nextTenSeconds(new Date())
    },
    $inc: {
      round: 1
    }
  })
  .exec();
};

const Board = mongoose.model('Board', BoardSchema);

module.exports = exports = Board;

<commit_msg>Make goal nearer<commit_after>'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = mongoose.Types.ObjectId;

const timer = require('../../../lib/timer');

const PlayerScheme = new Schema({
  id: { type: Schema.Types.ObjectId },
  name: { type: String, default: 'Ms. Anonymous'},
  x: { type: Number, },
  y: { type: Number, },
  _nextMove: {
    x: { type: Number, },
    y: { type: Number, },
  },
}, { _id : false });

const GoalSchema = new Schema({
  x: { type: Number, },
  y: { type: Number, },
  is_achieved: { type: Boolean, }
}, { _id : false });

let BoardSchema = new Schema({
  board: {
    width: { type: Number, default: 40, },
    height: { type: Number, default: 40, },
  },
  round: { type: Number, default: 0, },
  players: [PlayerScheme],
  numOfPlayers: { type: Number, default: 0, },
  goals: [GoalSchema],
  origin: {
    x: { type: Number, default: 5 },
    y: { type: Number, default: 5 },
  },
  status: {
    type: String, default: 'ongoing', enum: ['ongoing', 'lose', 'win'],
  },
  _nextRoundDeadline: { type: Date, required: true, },
});

/**
 * @returns Promise
 */
BoardSchema.statics.createBoardWithOnePlayer = function(playerIdHexString, playerName) {
  let boardId = new ObjectId();
  let playerId = new ObjectId(playerIdHexString);

  return this.create({
    _id: boardId,
    board: {
      width: 40,
      height: 40
    },
    players: [{
      id: playerId,
      name: playerName,
      x: 5,
      y: 5
    }],
    numOfPlayers: 1,
    goals: [{
      x: 10,
      y: 10,
      is_achieved: false
    }],
    _nextRoundDeadline: timer.nextTenSeconds(new Date())
  })
  .then(() => (boardId.toString()));
};

/**
 * @returns Promise
 */
BoardSchema.statics.findAvailableBoard = function() {
  return this.findOne({
    numOfPlayers: {
      $lt: 30000
    },
    status: 'ongoing'
  })
  .then((board) => {
    if (board)
      return board._id.toString();
    else
      return null;
  });
};

BoardSchema.statics.insertNewPlayer = function(boardIdHexString, playerIdHexString, playerName) {
  let boardId = new ObjectId(boardIdHexString);
  let playerId = new ObjectId(playerIdHexString);
  return this.update({
    _id: boardId
  }, {
    $push: {
      players: {
        id: playerId,
        name: playerName,
        x: 5,
        y: 5
      }
    },
    $inc: {
      numOfPlayers: 1
    }
  });
};

/**
 * @param {string} boardIdHexString
 * @param {string} playerIdHexString
 * @param {number} nextRound
 * @param {number} nextX
 * @param {number} nextY
 */
BoardSchema.statics.updateNextMove = function(boardIdHexString, playerIdHexString,
  nextRound, nextX, nextY) {
  let boardId = new ObjectId(boardIdHexString);
  let playerId = new ObjectId(playerIdHexString);

  return this.update({
    _id: boardId,
    'players.id': playerId,
    round: nextRound,
  }, {
    $set: {
      'players.$._nextMove': {
        x: nextX,
        y: nextY,
      }
    },
  });
};

BoardSchema.statics.removePlayer = function(boardIdHexString, playerIdHexString) {
  let boardId = new ObjectId(boardIdHexString);
  let playerId = new ObjectId(playerIdHexString);

  return this.update({
    _id: boardId,
    'players.id': playerId,
  }, {
    $unset: {
      'players.$': '',
    },
    $inc: {
      numOfPlayers: -1,
    }
  });
};

BoardSchema.methods.toTidyObject = function() {
  let result = this.toObject();
  result.id = result._id.toString();
  delete result._id;
  if ('__v' in result)
    delete result.__v;
  result.players = result.players
  .filter((player) => (player))
  .map((player) => ({
    id: player.id,
    name: player.name,
    x: player.x,
    y: player.y
  }));
  return result;
};

BoardSchema.methods.nextRound = function(players, status) {
  return this.update({
    $set: {
      players: players,
      status: status,
      _nextRoundDeadline: timer.nextTenSeconds(new Date())
    },
    $inc: {
      round: 1
    }
  })
  .exec();
};

const Board = mongoose.model('Board', BoardSchema);

module.exports = exports = Board;

<|endoftext|>


<commit_before>var React = require('react-native');
var {
  StyleSheet,
  PropTypes,
  NativeModules,
  requireNativeComponent
} = React;
var LayoutPropTypes = require('LayoutPropTypes');
var StyleSheetPropType = require('StyleSheetPropType');
var NativeMethodsMixin = require('NativeMethodsMixin');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var StyleSheetPropType = require('StyleSheetPropType');

var { FBLoginManager } = NativeModules;

var FBLogin = React.createClass({
  statics: {
    Events: FBLoginManager.Events,
  },

  propTypes: {
    style: StyleSheetPropType(LayoutPropTypes),
    permissions: PropTypes.array, // default: ["public_profile", "email"]
    onLogin: PropTypes.func,
    onLogout: PropTypes.func,
    onLoginFound: PropTypes.func,
    onLoginNotFound: PropTypes.func,
    onError: PropTypes.func,
    onCancel: PropTypes.func,
    onPermissionsMissing: PropTypes.func,
  },

  getInitialState: function(){
    return {
      credentials: null,
      subscriptions: [],
    };
  },

  mixins: [NativeMethodsMixin],

  componentWillMount: function(){
    var _this = this;
    var subscriptions = this.state.subscriptions;

    // For each event key in FBLoginManager constantsToExport
    // Create listener and call event handler from props
    // e.g.  this.props.onError, this.props.onLogin
    Object.keys(FBLoginManager.Events).forEach(function(event){
      subscriptions.push(RCTDeviceEventEmitter.addListener(
        FBLoginManager.Events[event],
        (eventData) => {
          // event handler defined? call it and pass along any event data
          var eventHandler = _this.props["on"+event];
          eventHandler && eventHandler(eventData);
        }
      ));
    })

    // Add listeners to state
    this.setState({ subscriptions : subscriptions });
  },

  componentWillUnmount: function(){
    var subscriptions = this.state.subscriptions;
    subscriptions.forEach(function(subscription){
      subscription.remove();
    });
  },

  componentDidMount: function(){
    var _this = this;
    FBLoginManager.getCredentials(function(error, data){
      if (!error) {
        _this.setState({ credentials : data.credentials });
      } else {
        _this.setState({ credentials : null });
      }
    });
  },

  render: function() {
    var props = {
      ...this.props,
      style: ([styles.base, this.props.style]),
    };

    return <RCTFBLogin {...props} />
  },
});

var RCTFBLogin = requireNativeComponent('RCTFBLogin', FBLogin);

var styles = StyleSheet.create({
  base: {
    width: 175,
    height: 30,
  },
});

module.exports = FBLogin;
<commit_msg>public api, coming soon? close #31<commit_after>var React = require('react-native');
var {
  StyleSheet,
  PropTypes,
  NativeModules,
  requireNativeComponent,

  // Once these are exposed, use them
  // LayoutPropTypes,
  // StyleSheetPropType,
  // NativeMethodsMixin,
  // RCTDeviceEventEmitter,
} = React;

// These are not yet exposed by the react-native package, so we must
// continue requiring them this way, which will cause warnings.
var LayoutPropTypes = require('LayoutPropTypes');
var StyleSheetPropType = require('StyleSheetPropType');
var NativeMethodsMixin = require('NativeMethodsMixin');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');

var { FBLoginManager } = NativeModules;

var FBLogin = React.createClass({
  statics: {
    Events: FBLoginManager.Events,
  },

  propTypes: {
    style: StyleSheetPropType(LayoutPropTypes),
    permissions: PropTypes.array, // default: ["public_profile", "email"]
    onLogin: PropTypes.func,
    onLogout: PropTypes.func,
    onLoginFound: PropTypes.func,
    onLoginNotFound: PropTypes.func,
    onError: PropTypes.func,
    onCancel: PropTypes.func,
    onPermissionsMissing: PropTypes.func,
  },

  getInitialState: function(){
    return {
      credentials: null,
      subscriptions: [],
    };
  },

  mixins: [NativeMethodsMixin],

  componentWillMount: function(){
    var _this = this;
    var subscriptions = this.state.subscriptions;

    // For each event key in FBLoginManager constantsToExport
    // Create listener and call event handler from props
    // e.g.  this.props.onError, this.props.onLogin
    Object.keys(FBLoginManager.Events).forEach(function(event){
      subscriptions.push(RCTDeviceEventEmitter.addListener(
        FBLoginManager.Events[event],
        (eventData) => {
          // event handler defined? call it and pass along any event data
          var eventHandler = _this.props["on"+event];
          eventHandler && eventHandler(eventData);
        }
      ));
    })

    // Add listeners to state
    this.setState({ subscriptions : subscriptions });
  },

  componentWillUnmount: function(){
    var subscriptions = this.state.subscriptions;
    subscriptions.forEach(function(subscription){
      subscription.remove();
    });
  },

  componentDidMount: function(){
    var _this = this;
    FBLoginManager.getCredentials(function(error, data){
      if (!error) {
        _this.setState({ credentials : data.credentials });
      } else {
        _this.setState({ credentials : null });
      }
    });
  },

  render: function() {
    var props = {
      ...this.props,
      style: ([styles.base, this.props.style]),
    };

    return <RCTFBLogin {...props} />
  },
});

var RCTFBLogin = requireNativeComponent('RCTFBLogin', FBLogin);

var styles = StyleSheet.create({
  base: {
    width: 175,
    height: 30,
  },
});

module.exports = FBLogin;
<|endoftext|>


<commit_before>import React from 'react'
import { shallow } from 'enzyme'
import DatasetSection from '../DatasetSection'
import datasetMock from '../../../fetch/__test__/dataset.json'
import { doneSince } from '../../../helpers/doneSince'

describe('<DatasetSection />', () => {
  let wrapper

  beforeEach(() => {
    wrapper = shallow(<DatasetSection dataset={datasetMock} />)
  })

  it('should display dataset title', () => {
    expect(wrapper.contains(datasetMock.metadata.title)).toBe(true)
  })

  it('should display dataset description', () => {
    expect(wrapper.contains(datasetMock.metadata.description)).toBe(true)
  })

  it('should display dataset type', () => {
    expect(wrapper.contains(datasetMock.metadata.type)).toBe(true)
  })

  it('should display dataset license', () => {
    expect(wrapper.contains(datasetMock.metadata.license)).toBe(true)
  })

  it('should display dataset revision date', () => {
    expect(wrapper.contains(doneSince(datasetMock.revisionDate))).toBe(true)
  })

  it('should display dataset id', () => {
    expect(wrapper.contains(datasetMock.metadata.id)).toBe(true)
  })

})
<commit_msg>Add test<commit_after>import React from 'react'
import { shallow } from 'enzyme'
import DatasetSection from '../DatasetSection'
import datasetMock from '../../../fetch/__test__/dataset.json'
import { doneSince } from '../../../helpers/doneSince'

describe('<DatasetSection />', () => {

  describe('When all metadata are defined', () => {
    let wrapper
    beforeEach(() => {
      wrapper = shallow(<DatasetSection dataset={datasetMock} />)
    })

    it('should display dataset title', () => {
      expect(wrapper.contains(datasetMock.metadata.title)).toBe(true)
    })

    it('should display dataset description', () => {
      expect(wrapper.contains(datasetMock.metadata.description)).toBe(true)
    })

    it('should display dataset type', () => {
      expect(wrapper.contains(datasetMock.metadata.type)).toBe(true)
    })

    it('should display dataset license', () => {
      expect(wrapper.contains(datasetMock.metadata.license)).toBe(true)
    })

    it('should display dataset revision date', () => {
      expect(wrapper.contains(doneSince(datasetMock.revisionDate))).toBe(true)
    })

    it('should display dataset id', () => {
      expect(wrapper.contains(datasetMock.metadata.id)).toBe(true)
    })
  })

  describe('When metadata are undefined', () => {
    let wrapper
    beforeEach(() => {
      datasetMock.metadata.license = undefined
      datasetMock.metadata.type = undefined
      wrapper = shallow(<DatasetSection dataset={datasetMock} />)
    })

    it('should display dataset type', () => {
      expect(wrapper.contains('unknown')).toBe(true)
    })

    it('should display dataset license', () => {
      expect(wrapper.contains('not determined')).toBe(true)
    })
  })

})
<|endoftext|>


<commit_before>window.AppConfig = {
  endpoint: "https://63434e18.ngrok.com/api/v1/"
}
<commit_msg>rm config example, unnecessary<commit_after><|endoftext|>


<commit_before>var express = require('express'),
    router = express.Router(),
    repo_correct = false;

/* GET Admin Repo Checks. */
router.get('/', function(req, res) {
    var data = {
        'os': {
            'available': true,
            'repos': {}
        },
        'openstack': {
            'available': false,
            'repos': {
                'x86_64': {
                    'missing': [
                        'SUSE OpenStack Cloud 7',
                        'SUSE OpenStack Cloud 7 Updates'
                    ]
                }
            }
        }
    };

    if (repo_correct) {
        data['openstack'] = {
            'available': true,
            'repos': {}
        }
    }
    repo_correct = !repo_correct;
    res.status(200).json(data);
});

module.exports = router;
<commit_msg>Update fake API response<commit_after>var express = require('express'),
    router = express.Router(),
    repo_correct = false;

/* GET Admin Repo Checks. */
router.get('/', function(req, res) {
    var data = {
        'os': {
            'available': true,
            'repos': {}
        },
        'openstack': {
            'available': false,
            'repos': {
                'x86_64': {
                    'missing': [
                        'SUSE-OpenStack-Cloud-7-Pool',
                        'SUSE-OpenStack-Cloud-7-Updates'
                    ]
                }
            }
        }
    };

    if (repo_correct) {
        data['openstack'] = {
            'available': true,
            'repos': {}
        }
    }
    repo_correct = !repo_correct;
    res.status(200).json(data);
});

module.exports = router;
<|endoftext|>


<commit_before>import _ from 'lodash';
import classNames from 'classNames';
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as appActions from '../actions/app';
import * as tweetActions from '../actions/tweet';
import * as mediaActions from '../actions/media';
import keyStringDetector from '../registries/keyStringDetector';
import Tweet from '../../domain/models/Tweet';
import Media from '../../domain/models/Media';
import { Accounts } from '../../domain/models/Accounts'
import * as dialogService from '../registries/dialogService';

class NewTweetContainer extends Component {

  constructor(props) {
    super(props);
    this.state = this.initialState();
  }

  onTextareaChanged(event) {
    const text = event.target.value;
    this.setState({ text: text }, () => {
      const isExceededLimitCharLength = this.getRestTextLength() < 0;
      this.setState({ isExceededLimitCharLength: isExceededLimitCharLength });
    });
  }

  onTextareaKeyDown(event) {
    if (keyStringDetector.detect(event) === 'Return') {
      event.preventDefault();
      this.onTweetSubmitted();
    }
  }

  onTweetSubmitted() {
    if (this.state.isExceededLimitCharLength) {
      return;
    }

    const { account, mediaToTweet } = this.props;
    const { postTweet }             = this.props.actions;

    postTweet(this.state.text, account.credential, mediaToTweet.medias);
    this.setState(this.initialState()); // TODO: init text area if succeed to tweet
  }

  onChooseImage() {
    const { medias } = this.props.mediaToTweet;
    if (!Media.appendsAdditionalMedia(medias)) return;

    dialogService.chooseImageFile({ extensions: Media.IMAGE_FILE_EXTENSIONS }, (filePaths) => {
      if (_.isUndefined(filePaths)) return;
      const media             = Media.build(filePaths[0]);
      const { uploadToTweet } = this.props.actions;
      uploadToTweet(media);
    });
  }

  getRestTextLength() {
    return Tweet.LIMIT_CHARA_LENGTH - this.state.text.length;
  }

  initialState() {
    return { text: '', isExceededLimitCharLength: false };
  }

  get tweetCounterClassName() {
    return classNames({
      'NewTweet-main-tweetCounter': true,
      'is-overLimit': this.state.isExceededLimitCharLength
    });
  }

  get tweetLabelClassName() {
    return classNames({
      'NewTweet-footer-tweetLabel': true,
      'is-active': this.state.text.length > 0,
      'is-overLimit': this.state.isExceededLimitCharLength
    });
  }

  get mediaButtonsClassName() {
    const { medias } = this.props.mediaToTweet;
    return classNames({
      'NewTweet-media-buttons': true,
      'is-overLimit': !Media.appendsAdditionalMedia(medias),
    });
  }

  decodeImage(media) {
    if (media === null) return;
    const base64    = media.toBase64();
    const extension = media.extension;
    return `data:image/${extension};base64,${base64}`;
  }

  onRemoveImage(media) {
    const { removeMedia } = this.props.actions;
    removeMedia(media.id)
  }

  get renderMedias() {
    const { medias } = this.props.mediaToTweet;

    return medias.map(media =>

    );
  }

  render() {
    const { account } = this.props;

    // TODO: render place

    return (

            <textarea
              autoFocus
              className="Editor-textarea"
              onChange={this.onTextareaChanged.bind(this)}
              onKeyDown={this.onTextareaKeyDown.bind(this)}
              value={this.state.text}>
            </textarea>

          {this.renderMedias}

            {this.getRestTextLength()}

            Tweet

    );
  }
}

NewTweetContainer.propTypes = {
  actions: PropTypes.object.isRequired,
  account: PropTypes.object.isRequired
};

function mapDispatchToProps(dispatch) {
  const actions = _.assign({}, appActions, tweetActions, mediaActions);
  return {
    actions: bindActionCreators(actions, dispatch)
  };
}

function mapStateToProps(state) {
  const { accounts, mediaToTweet } = state;
  const account                    = Accounts.fromObjects(accounts).primary;

  return {
    account: account,
    mediaToTweet: mediaToTweet,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(NewTweetContainer);
<commit_msg>Change Tweet label to active if media is attached<commit_after>import _ from 'lodash';
import classNames from 'classNames';
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as appActions from '../actions/app';
import * as tweetActions from '../actions/tweet';
import * as mediaActions from '../actions/media';
import keyStringDetector from '../registries/keyStringDetector';
import Tweet from '../../domain/models/Tweet';
import Media from '../../domain/models/Media';
import { Accounts } from '../../domain/models/Accounts'
import * as dialogService from '../registries/dialogService';

class NewTweetContainer extends Component {

  constructor(props) {
    super(props);
    this.state = this.initialState();
  }

  onTextareaChanged(event) {
    const text = event.target.value;
    this.setState({ text: text }, () => {
      const isExceededLimitCharLength = this.getRestTextLength() < 0;
      this.setState({ isExceededLimitCharLength: isExceededLimitCharLength });
    });
  }

  onTextareaKeyDown(event) {
    if (keyStringDetector.detect(event) === 'Return') {
      event.preventDefault();
      this.onTweetSubmitted();
    }
  }

  onTweetSubmitted() {
    if (this.state.isExceededLimitCharLength) {
      return;
    }

    const { account, mediaToTweet } = this.props;
    const { postTweet }             = this.props.actions;

    postTweet(this.state.text, account.credential, mediaToTweet.medias);
    this.setState(this.initialState()); // TODO: init text area if succeed to tweet
  }

  onChooseImage() {
    const { medias } = this.props.mediaToTweet;
    if (!Media.appendsAdditionalMedia(medias)) return;

    dialogService.chooseImageFile({ extensions: Media.IMAGE_FILE_EXTENSIONS }, (filePaths) => {
      if (_.isUndefined(filePaths)) return;
      const media             = Media.build(filePaths[0]);
      const { uploadToTweet } = this.props.actions;
      uploadToTweet(media);
    });
  }

  getRestTextLength() {
    return Tweet.LIMIT_CHARA_LENGTH - this.state.text.length;
  }

  initialState() {
    return { text: '', isExceededLimitCharLength: false };
  }

  get tweetCounterClassName() {
    return classNames({
      'NewTweet-main-tweetCounter': true,
      'is-overLimit': this.state.isExceededLimitCharLength
    });
  }

  get tweetLabelClassName() {
    const { medias } = this.props.mediaToTweet;
    return classNames({
      'NewTweet-footer-tweetLabel': true,
      'is-active': this.state.text.length > 0 || medias.length > 0,
      'is-overLimit': this.state.isExceededLimitCharLength
    });
  }

  get mediaButtonsClassName() {
    const { medias } = this.props.mediaToTweet;
    return classNames({
      'NewTweet-media-buttons': true,
      'is-overLimit': !Media.appendsAdditionalMedia(medias),
    });
  }

  decodeImage(media) {
    if (media === null) return;
    const base64    = media.toBase64();
    const extension = media.extension;
    return `data:image/${extension};base64,${base64}`;
  }

  onRemoveImage(media) {
    const { removeMedia } = this.props.actions;
    removeMedia(media.id)
  }

  get renderMedias() {
    const { medias } = this.props.mediaToTweet;

    return medias.map(media =>

    );
  }

  render() {
    const { account } = this.props;

    // TODO: render place

    return (

            <textarea
              autoFocus
              className="Editor-textarea"
              onChange={this.onTextareaChanged.bind(this)}
              onKeyDown={this.onTextareaKeyDown.bind(this)}
              value={this.state.text}>
            </textarea>

          {this.renderMedias}

            {this.getRestTextLength()}

            Tweet

    );
  }
}

NewTweetContainer.propTypes = {
  actions: PropTypes.object.isRequired,
  account: PropTypes.object.isRequired
};

function mapDispatchToProps(dispatch) {
  const actions = _.assign({}, appActions, tweetActions, mediaActions);
  return {
    actions: bindActionCreators(actions, dispatch)
  };
}

function mapStateToProps(state) {
  const { accounts, mediaToTweet } = state;
  const account                    = Accounts.fromObjects(accounts).primary;

  return {
    account: account,
    mediaToTweet: mediaToTweet,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(NewTweetContainer);
<|endoftext|>


<commit_before>/*
	Why You Should Love Star Wars
*/

var reason = getReason();

document.querySelector('#wrapper').style.height = window.innerHeight + 'px';

function getReason () {
	return reasons[
		Math.round(Math.random() * (reasons.length - 1))
	];
}

function gimme (lazyload, first) {

	if (reasons.length) {

		var main      = document.querySelector('#main'),
		    container = document.querySelector('#reason-view');

		if (!lazyload) {
			if (!first)	reason = getReason();

			main.style.display = 'none';
			container.style.display = 'block';
		}

		container.querySelector('img').src = reason.img;
		container.querySelector('p').innerHTML = reason.text;

	} else {
		console.info("Oh, apparently, the reasons are not loaded yet. Please, keep waiting.");
	}

}

gimme(true, true);
<commit_msg>WYSLSW: Not redisplay twice a reason<commit_after>/*
	Why You Should Love Star Wars
*/

var reason = getReason();

document.querySelector('#wrapper').style.height = window.innerHeight + 'px';

/**
 * Return a reason
 * @return {object} val - reason object
 */

function getReason () {

	var i   = Math.round(Math.random() * (reasons.length - 1)),
	    val = reasons[i];

	reasons.splice(i, 1);

	return val || {
		img: "https://media.giphy.com/media/pDTCmXCVXoMCY/giphy.gif",
		text: "Because there is no other reason for now. Why don't give yours on Github?"
	};

}

/**
 * Display one reason (text and picture)
 * @param {boolean} lazyload - true, if we lazyload the picture
 * @param {boolean} first - true, if first call
 */

function gimme (lazyload, first) {

	var main      = document.querySelector('#main'),
	    container = document.querySelector('#reason-view');

	if (!lazyload) {
		if (!first)	reason = getReason();

		main.style.display = 'none';
		container.style.display = 'block';
	}

	container.querySelector('img').src = reason.img;
	container.querySelector('p').innerHTML = reason.text;

}

gimme(true, true);
<|endoftext|>