<commit_before>
var request = require('request');
var glob = require('glob');
var fs = require('fs.extra');
var mkdirp = require('mkdirp');
var server = require('./server.js');

// Sadly, our setup fatals when doing multiple concurrent requests
// I don't have the time to dig into why, it's easier to just serialize
// requests.
var queue = (function() {
  var is_executing = false;
  var queue = [];
  function push(fn) {
    queue.push(fn);
    execute();
  }
  function execute() {
    if (is_executing) {
      return;
    }
    if (queue.length === 0) {
      return;
    }
    var fn = queue.shift();
    is_executing = true;
    fn(function() {
      is_executing = false;
      execute();
    });
  }
  return {push: push};
})();

glob('src/**/*.*', function(er, files) {
  files.forEach(function(file) {
    var targetFile = file.replace(/^src/, 'build');

    if (file.match(/\.js$/)) {
      targetFile = targetFile.replace(/\.js$/, '.html');
      queue.push(function(cb) {
        request('http://localhost:8079/' + targetFile.replace(/^build\//, ''), function(error, response, body) {
          mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), ''));
          fs.writeFileSync(targetFile, body);
          cb();
        });
      });
    } else {
      queue.push(function(cb) {
        mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), ''));
        fs.copy(file, targetFile, cb);
      });
    }
  });

  queue.push(function(cb) {
    server.close();
    console.log('It is live at: http://facebook.github.io/react-native/')
    cb();
  });
});
<commit_msg>Attempt #5<commit_after>
var request = require('request');
var glob = require('glob');
var fs = require('fs.extra');
var mkdirp = require('mkdirp');
var server = require('./server.js');

require('./convert.js')();

// Sadly, our setup fatals when doing multiple concurrent requests
// I don't have the time to dig into why, it's easier to just serialize
// requests.
var queue = (function() {
  var is_executing = false;
  var queue = [];
  function push(fn) {
    queue.push(fn);
    execute();
  }
  function execute() {
    if (is_executing) {
      return;
    }
    if (queue.length === 0) {
      return;
    }
    var fn = queue.shift();
    is_executing = true;
    fn(function() {
      is_executing = false;
      execute();
    });
  }
  return {push: push};
})();

glob('src/**/*.*', function(er, files) {
  files.forEach(function(file) {
    var targetFile = file.replace(/^src/, 'build');

    if (file.match(/\.js$/)) {
      targetFile = targetFile.replace(/\.js$/, '.html');
      queue.push(function(cb) {
        request('http://localhost:8079/' + targetFile.replace(/^build\//, ''), function(error, response, body) {
          mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), ''));
          fs.writeFileSync(targetFile, body);
          cb();
        });
      });
    } else {
      queue.push(function(cb) {
        mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), ''));
        fs.copy(file, targetFile, cb);
      });
    }
  });

  queue.push(function(cb) {
    server.close();
    console.log('It is live at: http://facebook.github.io/react-native/')
    cb();
  });
});
<|endoftext|>


<commit_before>M.Themes.registerTemplateForTheme(M.Themes.DEFAULT_THEME, 'switch-layout', '

');

M.SwitchLayout = M.Layout.extend({

    _type: 'M.SwitchLayout',

    template: M.Themes.getTemplateByName('switch-layout'),

    currentPage: null,

    applyViews: function( settings ){

        var current = $('.m-page-current');

        var next = $('.m-page:not(.m-page-current)');

        var selector = '';

        if(this.currentPage === null || this.currentPage === 'content_page2'){
            this.currentPage = 'content_page1';

        } else if(this.currentPage === 'content_page1'){
            this.currentPage = 'content_page2';
        }

        if(!this.childViews[this.currentPage]){
            this.addChildView(this.currentPage, settings.content);
        } else if(this.childViews[this.currentPage] !== settings.content){
            this.addChildView(this.currentPage, settings.content);
        }

        this.$el.find('[data-childviews="' + this.currentPage + '"]').html(settings.content.render().$el);

        return this;
    },

    _render: function(){
        M.Layout.prototype._render.apply(this, arguments);
        if(this._firstRender){
            $('body').html(this.$el);
        }
    },

    _postRender: function(){
        if(this._firstRender){
            M.PageTransitions.init();
        }
    },

    startTransition: function(){
        M.PageTransitions.startTransition();
    }
})
<commit_msg>fixed layout bug<commit_after>M.Themes.registerTemplateForTheme(M.Themes.DEFAULT_THEME, 'switch-layout', '

');

M.SwitchLayout = M.Layout.extend({

    _type: 'M.SwitchLayout',

    template: M.Themes.getTemplateByName('switch-layout'),

    currentPage: null,

    applyViews: function( settings ){

        var current = $('.m-page-current');

        var next = $('.m-page:not(.m-page-current)');

        var selector = '';

        if(this.currentPage === null || this.currentPage === 'content_page2'){
            this.currentPage = 'content_page1';

        } else if(this.currentPage === 'content_page1'){
            this.currentPage = 'content_page2';
        }

        if(!this.childViews[this.currentPage]){
            this.addChildView(this.currentPage, settings.content);
        } else if(this.childViews[this.currentPage] !== settings.content){
            this.addChildView(this.currentPage, settings.content);
        }

        this.$el.find('[data-childviews="' + this.currentPage + '"]').append(settings.content.render().$el);

        return this;
    },

    _render: function(){
        M.Layout.prototype._render.apply(this, arguments);
        if(this._firstRender){
            $('body').html(this.$el);
        }
    },

    _postRender: function(){
        if(this._firstRender){
            M.PageTransitions.init();
        }
    },

    startTransition: function(){
        M.PageTransitions.startTransition();
    }
})
<|endoftext|>


<commit_before>var React = require('react');
var cx = require('classnames');

var utils = require('../lib/widget-utils.js');

var defaultTemplate = `
  <input type="checkbox" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}} {{count}}
`;

/**
 * Instantiate a list of refinements based on a facet
 * @param  {String|DOMElement} options.container Valid CSS Selector as a string or DOMElement
 * @param  {String} options.facetName Name of the attribute for faceting
 * @param  {String} options.operator How to apply refinements. Possible values: `or`, `and`
 * @param  {String[]} [options.sortBy=['count:desc']] How to sort refinements. Possible values: `count|isRefined|name:asc|desc`
 * @param  {String} [options.limit=100] How much facet values to get.
 * @param  {String|String[]} [options.rootClass=null] CSS class(es) for the root `<ul>` element
 * @param  {String|String[]} [options.itemClass=null] CSS class(es) for the item `<li>` element
 * @param  {String|Function} [options.template] Item template, provided with `name`, `count`, `isRefined`
 * @param  {String|Function} [options.singleRefine=true] Are multiple refinements allowed or only one at the same time. You can use this
 *                                                       to build radio based refinement lists for example.
 * @return {Object}
 */
function refinementList({
    container = null,
    facetName = null,
    operator = null,
    sortBy = ['count:desc'],
    limit = 100,
    rootClass = null,
    itemClass = null,
    template = defaultTemplate,
    singleRefine = false
  }) {
  var RefinementList = require('../components/RefinementList');

  var containerNode = utils.getContainerNode(container);
  var usage = 'Usage: refinementList({container, facetName, operator[sortBy, limit, rootClass, itemClass, template]})';

  if (container === null ||
    facetName === null ||
    // operator is mandatory when multiple refines allowed
    (operator === null && singleRefine === false) ||
    // operator is not allowed when single refine enabled
    (operator !== null && singleRefine === true)) {
    throw new Error(usage);
  }

  operator = operator.toLowerCase();
  if (operator !== 'and' && operator !== 'or') {
    throw new Error(usage);
  }

  return {
    getConfiguration: () => ({
      [operator === 'and' ? 'facets' : 'disjunctiveFacets']: [facetName]
    }),
    render: function(results, state, helper) {
      React.render(
        <RefinementList
          rootClass={cx(rootClass)}
          itemClass={cx(itemClass)}
          facetValues={results.getFacetValues(facetName, {sortBy: sortBy}).slice(0, limit)}
          template={template}
          toggleRefine={toggleRefine.bind(null, helper, singleRefine, facetName)}
        />,
        containerNode
      );
    }
  };
}

function toggleRefine(helper, singleRefine, facetName, facetValue) {
  if (singleRefine) {
    helper.clearRefinement(facetName);
  }

  helper
    .toggleRefinement(facetName, facetValue)
    .search();
}

module.exports = refinementList;
<commit_msg>fix: toggleRefine was no more working<commit_after>var React = require('react');
var cx = require('classnames');

var utils = require('../lib/widget-utils.js');

var defaultTemplate = `
  <input type="checkbox" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}} {{count}}
`;

/**
 * Instantiate a list of refinements based on a facet
 * @param  {String|DOMElement} options.container Valid CSS Selector as a string or DOMElement
 * @param  {String} options.facetName Name of the attribute for faceting
 * @param  {String} options.operator How to apply refinements. Possible values: `or`, `and`
 * @param  {String[]} [options.sortBy=['count:desc']] How to sort refinements. Possible values: `count|isRefined|name:asc|desc`
 * @param  {String} [options.limit=100] How much facet values to get.
 * @param  {String|String[]} [options.rootClass=null] CSS class(es) for the root `<ul>` element
 * @param  {String|String[]} [options.itemClass=null] CSS class(es) for the item `<li>` element
 * @param  {String|Function} [options.template] Item template, provided with `name`, `count`, `isRefined`
 * @param  {String|Function} [options.singleRefine=true] Are multiple refinements allowed or only one at the same time. You can use this
 *                                                       to build radio based refinement lists for example.
 * @return {Object}
 */
function refinementList({
    container = null,
    facetName = null,
    operator = null,
    sortBy = ['count:desc'],
    limit = 100,
    rootClass = null,
    itemClass = null,
    template = defaultTemplate,
    singleRefine = false
  }) {
  var RefinementList = require('../components/RefinementList');

  var containerNode = utils.getContainerNode(container);
  var usage = 'Usage: refinementList({container, facetName, operator[sortBy, limit, rootClass, itemClass, template]})';

  if (container === null ||
    facetName === null ||
    // operator is mandatory when multiple refines allowed
    (operator === null && singleRefine === false) ||
    // operator is not allowed when single refine enabled
    (operator !== null && singleRefine === true)) {
    throw new Error(usage);
  }

  operator = operator.toLowerCase();
  if (operator !== 'and' && operator !== 'or') {
    throw new Error(usage);
  }

  return {
    getConfiguration: () => ({
      [operator === 'and' ? 'facets' : 'disjunctiveFacets']: [facetName]
    }),
    render: function(results, state, helper) {
      React.render(
        <RefinementList
          rootClass={cx(rootClass)}
          itemClass={cx(itemClass)}
          facetValues={results.getFacetValues(facetName, {sortBy: sortBy}).slice(0, limit)}
          template={template}
          toggleRefinement={toggleRefinement.bind(null, helper, singleRefine, facetName)}
        />,
        containerNode
      );
    }
  };
}

function toggleRefinement(helper, singleRefine, facetName, facetValue) {
  if (singleRefine) {
    helper.clearRefinement(facetName);
  }

  helper
    .toggleRefinement(facetName, facetValue)
    .search();
}

module.exports = refinementList;
<|endoftext|>


<commit_before>import react, { PropTypes } from 'react'
import { Button, Form, Table } from 'react-bootstrap'
import Reducer from './reducer'

class table extends Component {
    render() {
        let player = Object.keys(initState.players).map((id) => {
            return (

                    {initState.players[id].name}
                    {initState.players[id].surname}
                    {initState.players[id].knowname}
                    {initState.players[id].shirtNumb}
                    {initState.players[id].role}

                        <button
                            type="button"
                            className="btn btn-info btn-xs"
                            onClick={this.editPlayer.bind(this, player.id)}
                            >
                            Edit
                        </button>
                        <button
                            type="button"
                            className="btn btn-danger btn-xs"
                            onClick={this.deletePlayer.bind(this, player.id)}>
                            Delete
                        </button>

            )
        })
        return (

Player List

                                    Name
                                    Surname
                                    Knowname
                                    Shirt Number
                                    Role

                                {players}

        )
    }
    deletePlayer(id) {
        store.dispatch({
            type: 'REMOVE_PLAYER',
            id
        })
    }
}

class form extends Component {
    render() {
        let shirtNumber = this.props.data.menu.shirtNumber
        let role = this.props.data.menu.role

        let playerNumber = shirNumber.map((number, key) => {
            return <option key={key} value={number}>{number}</option>
        })

        let playerRole = role.map((role, key) => {
            return <option key={key} value={role}>{role}</option>
        })

        return (

                    <form
                        className="form-horizontal"
                        onSubmit={this.addingPlayer.bind(this)}>

Insert the Player

                                First Name

                                    <input
                                        required
                                        className="form-control"
                                        ref='name'
                                        type="text"
                                    />

                                Last Name

                                    <input
                                        required
                                        className="form-control"
                                        ref="surname"
                                        type="text"
                                    />

                                Know name

                                    <input
                                        required
                                        className="form-control"
                                        ref="knowname"
                                        type="text"
                                    />

                                Shirt Number

                                    <select
                                        required
                                        className="form-control"
                                        ref="shirtNumb"
                                        name="shirtNumber">
                                        <option defaultValue=''>Please Select the Shirt Number</option>
                                        {playerNumber}
                                    </select>

                                Role

                                    <select
                                        required
                                        className="form-control"
                                        ref="role"
                                        name="role">
                                        <option defaultValue=''>Please Select a Role</option>
                                        {playerRole}
                                    </select>

                            <input className="btn btn-succes" type="submit" value="Insert The Player" />
                        </form>

        )
    }
    addingPlayer(e) {
        e.preventDefault()
        let newPlayer = {
            id: this.props.data.players.lenght + 1,
            name: this.refs.name.value,
            surname: this.refs.surname.value,
            knowname: this.refs.knowname.value,
            shirtNumb: this.refs.shirtNumb.value,
            role: this.refs.role.value
        }
        store.dispatch({
            type: 'ADD_PLAYER',
            newPlayer
        })
        this.refs.name.value = '',
        this.refs.surname.value = '',
        this.refs.knowname.value = '',
        this.refs.shirtNumb.value = 'Please Select the Shirt Number',
        this.refs.role.value = 'Please Select a Role'
    }

}<commit_msg>Modificato component action newPlayer<commit_after>import react, { PropTypes } from 'react'
import { Button, Form, Table } from 'react-bootstrap'
import Reducer from './reducer'

class table extends Component {
    render() {
        let player = Object.keys(initState.players).map((id) => {
            return (

                    {initState.players[id].name}
                    {initState.players[id].surname}
                    {initState.players[id].knowname}
                    {initState.players[id].shirtNumb}
                    {initState.players[id].role}

                        <button
                            type="button"
                            className="btn btn-info btn-xs"
                            onClick={this.editPlayer.bind(this, player.id)}
                            >
                            Edit
                        </button>
                        <button
                            type="button"
                            className="btn btn-danger btn-xs"
                            onClick={this.deletePlayer.bind(this, player.id)}>
                            Delete
                        </button>

            )
        })
        return (

Player List

                                    Name
                                    Surname
                                    Knowname
                                    Shirt Number
                                    Role

                                {players}

        )
    }
  /*  deletePlayer(id) {
        store.dispatch({
            type: 'REMOVE_PLAYER',
            id
        })
    };
    editPlayer(text) {
      store.dispatch({
        type: 'EDIT_PLAYER',
        text
      })
    } */
}

class form extends Component {
    render() {
        let shirtNumber = this.props.data.menu.shirtNumber
        let role = this.props.data.menu.role

        let playerNumber = shirNumber.map((number, key) => {
            return <option key={key} value={number}>{number}</option>
        })

        let playerRole = role.map((role, key) => {
            return <option key={key} value={role}>{role}</option>
        })

        return (

                    <form
                        className="form-horizontal"
                        onSubmit={this.addingPlayer.bind(this)}>

Insert the Player

                                First Name

                                    <input
                                        required
                                        className="form-control"
                                        ref='name'
                                        type="text"
                                    />

                                Last Name

                                    <input
                                        required
                                        className="form-control"
                                        ref="surname"
                                        type="text"
                                    />

                                Know name

                                    <input
                                        required
                                        className="form-control"
                                        ref="knowname"
                                        type="text"
                                    />

                                Shirt Number

                                    <select
                                        required
                                        className="form-control"
                                        ref="shirtNumb"
                                        name="shirtNumber">
                                        <option defaultValue=''>Please Select the Shirt Number</option>
                                        {playerNumber}
                                    </select>

                                Role

                                    <select
                                        required
                                        className="form-control"
                                        ref="role"
                                        name="role">
                                        <option defaultValue=''>Please Select a Role</option>
                                        {playerRole}
                                    </select>

                            <input className="btn btn-succes" type="submit" value="Insert The Player" />
                        </form>

        )
    }
    /* addingPlayer(e) {
        e.preventDefault()
        let newPlayer = {
            id: this.props.data.players.lenght + 1,
            name: this.refs.name.value,
            surname: this.refs.surname.value,
            knowname: this.refs.knowname.value,
            shirtNumb: this.refs.shirtNumb.value,
            role: this.refs.role.value
        }
        store.dispatch({
            type: 'ADD_PLAYER',
            newPlayer
        })
        this.refs.name.value = '',
        this.refs.surname.value = '',
        this.refs.knowname.value = '',
        this.refs.shirtNumb.value = 'Please Select the Shirt Number',
        this.refs.role.value = 'Please Select a Role'
    } */
    let newPlayer = Object.assign({}, values, {
      id,
      name: values.name.filter(n => n),
      surname: values.surname.filter(s => s),
      knowname: values.knowname.filter(k => k),
      shirtNumb: values.shirtNumb.filter(h => h),
      role: values.role.filter(r => r)
    });
    dispatch(action.addPlayer(newPlayer));
}
<|endoftext|>


<commit_before>import { createWidget } from 'discourse/widgets/widget';
import { iconNode } from 'discourse/helpers/fa-icon-node';
import { avatarImg } from 'discourse/widgets/post';
import DiscourseURL from 'discourse/lib/url';
import { wantsNewWindow } from 'discourse/lib/intercept-click';

import { h } from 'virtual-dom';

const dropdown = {
  buildClasses(attrs) {
    if (attrs.active) { return "active"; }
  },

  click(e) {
    if (wantsNewWindow(e)) { return; }
    e.preventDefault();
    if (!this.attrs.active) {
      this.sendWidgetAction(this.attrs.action);
    }
  }
};

createWidget('header-notifications', {
  settings: {
    avatarSize: 'medium'
  },

  html(attrs) {
    const { currentUser } = this;

    const contents = [ avatarImg(this.settings.avatarSize, {
      template: currentUser.get('avatar_template'),
      username: currentUser.get('username')
    }) ];

    const unreadNotifications = currentUser.get('unread_notifications');
    if (!!unreadNotifications) {
      contents.push(this.attach('link', { action: attrs.action,
                                          className: 'badge-notification unread-notifications',
                                          rawLabel: unreadNotifications }));
    }

    const unreadPMs = currentUser.get('unread_private_messages');
    if (!!unreadPMs) {
      contents.push(this.attach('link', { action: attrs.action,
                                          className: 'badge-notification unread-private-messages',
                                          rawLabel: unreadPMs }));
    }

    return contents;
  }
});

createWidget('user-dropdown', jQuery.extend({
  tagName: 'li.header-dropdown-toggle.current-user',

  buildId() {
    return 'current-user';
  },

  html(attrs) {
    const { currentUser } = this;

    return h('a.icon', { attributes: { href: currentUser.get('path'), 'data-auto-route': true } },
             this.attach('header-notifications', attrs));
  }
}, dropdown));

createWidget('header-dropdown', jQuery.extend({
  tagName: 'li.header-dropdown-toggle',

  html(attrs) {
    const title = I18n.t(attrs.title);

    const body = [iconNode(attrs.icon)];
    if (attrs.contents) {
      body.push(attrs.contents.call(this));
    }

    return h('a.icon', { attributes: { href: attrs.href,
                                       'data-auto-route': true,
                                       title,
                                       'aria-label': title,
                                       id: attrs.iconId } }, body);
  }
}, dropdown));

createWidget('header-icons', {
  tagName: 'ul.icons.clearfix',

  buildAttributes() {
    return { role: 'navigation' };
  },

  html(attrs) {
    const hamburger = this.attach('header-dropdown', {
                        title: 'hamburger_menu',
                        icon: 'bars',
                        iconId: 'toggle-hamburger-menu',
                        active: attrs.hamburgerVisible,
                        action: 'toggleHamburger',
                        contents() {
                          if (!attrs.flagCount) { return; }
                          return this.attach('link', {
                            href: '/admin/flags/active',
                            title: 'notifications.total_flagged',
                            rawLabel: attrs.flagCount,
                            className: 'badge-notification flagged-posts'
                          });
                        }
                      });

    const search = this.attach('header-dropdown', {
                     title: 'search.title',
                     icon: 'search',
                     iconId: 'search-button',
                     action: 'toggleSearchMenu',
                     active: attrs.searchVisible,
                     href: '/search'
                   });

    const icons = [search, hamburger];
    if (this.currentUser) {
      icons.push(this.attach('user-dropdown', { active: attrs.userVisible,
                                                action: 'toggleUserMenu' }));
    }

    return icons;
  },
});

createWidget('header-buttons', {
  tagName: 'span',

  html(attrs) {
    if (this.currentUser) { return; }

    const buttons = [];

    if (attrs.canSignUp && !attrs.topic) {
      buttons.push(this.attach('button', { label: "sign_up",
                                           className: 'btn-primary btn-small sign-up-button',
                                           action: "showCreateAccount" }));
    }

    buttons.push(this.attach('button', { label: 'log_in',
                                         className: 'btn-primary btn-small login-button',
                                         action: 'showLogin',
                                         icon: 'user' }));
    return buttons;
  }
});

export default createWidget('header', {
  tagName: 'header.d-header.clearfix',
  buildKey: () => `header`,

  defaultState() {
    return { searchVisible: false,
             hamburgerVisible: false,
             userVisible: false,
             contextEnabled: false };
  },

  html(attrs, state) {
    const panels = [this.attach('header-buttons', attrs),
                    this.attach('header-icons', { hamburgerVisible: state.hamburgerVisible,
                                                  userVisible: state.userVisible,
                                                  searchVisible: state.searchVisible,
                                                  flagCount: attrs.flagCount })];

    if (state.searchVisible) {
      panels.push(this.attach('search-menu', { contextEnabled: state.contextEnabled }));
    } else if (state.hamburgerVisible) {
      panels.push(this.attach('hamburger-menu'));
    } else if (state.userVisible) {
      panels.push(this.attach('user-menu'));
    }

    const contents = [ this.attach('home-logo', { minimized: !!attrs.topic }),
                       h('div.panel.clearfix', panels) ];

    if (attrs.topic) {
      contents.push(this.attach('header-topic-info', attrs));
    }

    return h('div.wrap', h('div.contents.clearfix', contents));
  },

  updateHighlight() {
    if (!this.state.searchVisible) {
      const service = this.container.lookup('search-service:main');
      service.set('highlightTerm', '');
    }
  },

  closeAll() {
    this.state.userVisible = false;
    this.state.hamburgerVisible = false;
    this.state.searchVisible = false;
  },

  linkClickedEvent() {
    this.closeAll();
    this.updateHighlight();
  },

  toggleSearchMenu() {
    if (this.site.mobileView) {
      const searchService = this.container.lookup('search-service:main');
      const context = searchService.get('searchContext');
      var params = "";

      if (context) {
        params = `?context=${context.type}&context_id=${context.id}&skip_context=true`;
      }

      return DiscourseURL.routeTo('/search' + params);
    }

    this.state.searchVisible = !this.state.searchVisible;
    this.updateHighlight();

    if (this.state.searchVisible) {
      Ember.run.schedule('afterRender', () => $('#search-term').focus().select());
    }
  },

  toggleUserMenu() {
    this.state.userVisible = !this.state.userVisible;
  },

  toggleHamburger() {
    this.state.hamburgerVisible = !this.state.hamburgerVisible;
  },

  togglePageSearch() {
    const { state } = this;

    state.contextEnabled = false;

    const currentPath = this.container.lookup('controller:application').get('currentPath');
    const blacklist = [ /^discovery\.categories/ ];
    const whitelist = [ /^topic\./ ];
    const check = function(regex) { return !!currentPath.match(regex); };
    let showSearch = whitelist.any(check) && !blacklist.any(check);

    // If we're viewing a topic, only intercept search if there are cloaked posts
    if (showSearch && currentPath.match(/^topic\./)) {
      showSearch = ($('.topic-post .cooked, .small-action:not(.time-gap)').length <
                    this.container.lookup('controller:topic').get('model.postStream.stream.length'));
    }

    if (state.searchVisible) {
      this.toggleSearchMenu();
      return showSearch;
    }

    if (showSearch) {
      state.contextEnabled = true;
      this.toggleSearchMenu();
      return false;
    }

    return true;
  },

  searchMenuContextChanged(value) {
    this.state.contextEnabled = value;
  },

  domClean() {
    const { state } = this;

    if (state.searchVisible || state.hamburgerVisible || state.userVisible) {
      this.closeAll();
    }
  },

  headerKeyboardTrigger(msg) {
    switch(msg.type) {
      case 'search':
        this.toggleSearchMenu();
        break;
      case 'user':
        this.toggleUserMenu();
        break;
      case 'hamburger':
        this.toggleHamburger();
        break;
      case 'page-search':
        if (!this.togglePageSearch()) {
          msg.event.preventDefault();
          msg.event.stopPropagation();
        }
        break;
    }
  }

});
<commit_msg>FIX: Make links work with subfolder installs.<commit_after>import { createWidget } from 'discourse/widgets/widget';
import { iconNode } from 'discourse/helpers/fa-icon-node';
import { avatarImg } from 'discourse/widgets/post';
import DiscourseURL from 'discourse/lib/url';
import { wantsNewWindow } from 'discourse/lib/intercept-click';

import { h } from 'virtual-dom';

const dropdown = {
  buildClasses(attrs) {
    if (attrs.active) { return "active"; }
  },

  click(e) {
    if (wantsNewWindow(e)) { return; }
    e.preventDefault();
    if (!this.attrs.active) {
      this.sendWidgetAction(this.attrs.action);
    }
  }
};

createWidget('header-notifications', {
  settings: {
    avatarSize: 'medium'
  },

  html(attrs) {
    const { currentUser } = this;

    const contents = [ avatarImg(this.settings.avatarSize, {
      template: currentUser.get('avatar_template'),
      username: currentUser.get('username')
    }) ];

    const unreadNotifications = currentUser.get('unread_notifications');
    if (!!unreadNotifications) {
      contents.push(this.attach('link', { action: attrs.action,
                                          className: 'badge-notification unread-notifications',
                                          rawLabel: unreadNotifications }));
    }

    const unreadPMs = currentUser.get('unread_private_messages');
    if (!!unreadPMs) {
      contents.push(this.attach('link', { action: attrs.action,
                                          className: 'badge-notification unread-private-messages',
                                          rawLabel: unreadPMs }));
    }

    return contents;
  }
});

createWidget('user-dropdown', jQuery.extend({
  tagName: 'li.header-dropdown-toggle.current-user',

  buildId() {
    return 'current-user';
  },

  html(attrs) {
    const { currentUser } = this;

    return h('a.icon', { attributes: { href: currentUser.get('path'), 'data-auto-route': true } },
             this.attach('header-notifications', attrs));
  }
}, dropdown));

createWidget('header-dropdown', jQuery.extend({
  tagName: 'li.header-dropdown-toggle',

  html(attrs) {
    const title = I18n.t(attrs.title);

    const body = [iconNode(attrs.icon)];
    if (attrs.contents) {
      body.push(attrs.contents.call(this));
    }

    return h('a.icon', { attributes: { href: attrs.href,
                                       'data-auto-route': true,
                                       title,
                                       'aria-label': title,
                                       id: attrs.iconId } }, body);
  }
}, dropdown));

createWidget('header-icons', {
  tagName: 'ul.icons.clearfix',

  buildAttributes() {
    return { role: 'navigation' };
  },

  html(attrs) {
    const hamburger = this.attach('header-dropdown', {
                        title: 'hamburger_menu',
                        icon: 'bars',
                        iconId: 'toggle-hamburger-menu',
                        active: attrs.hamburgerVisible,
                        action: 'toggleHamburger',
                        contents() {
                          if (!attrs.flagCount) { return; }
                          return this.attach('link', {
                            href: Discourse.getURL('/admin/flags/active'),
                            title: 'notifications.total_flagged',
                            rawLabel: attrs.flagCount,
                            className: 'badge-notification flagged-posts'
                          });
                        }
                      });

    const search = this.attach('header-dropdown', {
                     title: 'search.title',
                     icon: 'search',
                     iconId: 'search-button',
                     action: 'toggleSearchMenu',
                     active: attrs.searchVisible,
                     href: Discourse.getURL('/search')
                   });

    const icons = [search, hamburger];
    if (this.currentUser) {
      icons.push(this.attach('user-dropdown', { active: attrs.userVisible,
                                                action: 'toggleUserMenu' }));
    }

    return icons;
  },
});

createWidget('header-buttons', {
  tagName: 'span',

  html(attrs) {
    if (this.currentUser) { return; }

    const buttons = [];

    if (attrs.canSignUp && !attrs.topic) {
      buttons.push(this.attach('button', { label: "sign_up",
                                           className: 'btn-primary btn-small sign-up-button',
                                           action: "showCreateAccount" }));
    }

    buttons.push(this.attach('button', { label: 'log_in',
                                         className: 'btn-primary btn-small login-button',
                                         action: 'showLogin',
                                         icon: 'user' }));
    return buttons;
  }
});

export default createWidget('header', {
  tagName: 'header.d-header.clearfix',
  buildKey: () => `header`,

  defaultState() {
    return { searchVisible: false,
             hamburgerVisible: false,
             userVisible: false,
             contextEnabled: false };
  },

  html(attrs, state) {
    const panels = [this.attach('header-buttons', attrs),
                    this.attach('header-icons', { hamburgerVisible: state.hamburgerVisible,
                                                  userVisible: state.userVisible,
                                                  searchVisible: state.searchVisible,
                                                  flagCount: attrs.flagCount })];

    if (state.searchVisible) {
      panels.push(this.attach('search-menu', { contextEnabled: state.contextEnabled }));
    } else if (state.hamburgerVisible) {
      panels.push(this.attach('hamburger-menu'));
    } else if (state.userVisible) {
      panels.push(this.attach('user-menu'));
    }

    const contents = [ this.attach('home-logo', { minimized: !!attrs.topic }),
                       h('div.panel.clearfix', panels) ];

    if (attrs.topic) {
      contents.push(this.attach('header-topic-info', attrs));
    }

    return h('div.wrap', h('div.contents.clearfix', contents));
  },

  updateHighlight() {
    if (!this.state.searchVisible) {
      const service = this.container.lookup('search-service:main');
      service.set('highlightTerm', '');
    }
  },

  closeAll() {
    this.state.userVisible = false;
    this.state.hamburgerVisible = false;
    this.state.searchVisible = false;
  },

  linkClickedEvent() {
    this.closeAll();
    this.updateHighlight();
  },

  toggleSearchMenu() {
    if (this.site.mobileView) {
      const searchService = this.container.lookup('search-service:main');
      const context = searchService.get('searchContext');
      var params = "";

      if (context) {
        params = `?context=${context.type}&context_id=${context.id}&skip_context=true`;
      }

      return DiscourseURL.routeTo('/search' + params);
    }

    this.state.searchVisible = !this.state.searchVisible;
    this.updateHighlight();

    if (this.state.searchVisible) {
      Ember.run.schedule('afterRender', () => $('#search-term').focus().select());
    }
  },

  toggleUserMenu() {
    this.state.userVisible = !this.state.userVisible;
  },

  toggleHamburger() {
    this.state.hamburgerVisible = !this.state.hamburgerVisible;
  },

  togglePageSearch() {
    const { state } = this;

    state.contextEnabled = false;

    const currentPath = this.container.lookup('controller:application').get('currentPath');
    const blacklist = [ /^discovery\.categories/ ];
    const whitelist = [ /^topic\./ ];
    const check = function(regex) { return !!currentPath.match(regex); };
    let showSearch = whitelist.any(check) && !blacklist.any(check);

    // If we're viewing a topic, only intercept search if there are cloaked posts
    if (showSearch && currentPath.match(/^topic\./)) {
      showSearch = ($('.topic-post .cooked, .small-action:not(.time-gap)').length <
                    this.container.lookup('controller:topic').get('model.postStream.stream.length'));
    }

    if (state.searchVisible) {
      this.toggleSearchMenu();
      return showSearch;
    }

    if (showSearch) {
      state.contextEnabled = true;
      this.toggleSearchMenu();
      return false;
    }

    return true;
  },

  searchMenuContextChanged(value) {
    this.state.contextEnabled = value;
  },

  domClean() {
    const { state } = this;

    if (state.searchVisible || state.hamburgerVisible || state.userVisible) {
      this.closeAll();
    }
  },

  headerKeyboardTrigger(msg) {
    switch(msg.type) {
      case 'search':
        this.toggleSearchMenu();
        break;
      case 'user':
        this.toggleUserMenu();
        break;
      case 'hamburger':
        this.toggleHamburger();
        break;
      case 'page-search':
        if (!this.togglePageSearch()) {
          msg.event.preventDefault();
          msg.event.stopPropagation();
        }
        break;
    }
  }

});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require .
//= require_tree .
<commit_msg>nicely working for landing pages<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require landing_page_eng/jquery.cycle.all
//= require landing_page_eng/landing_pages
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
  Dimensions,
  ScrollView,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

import Day from './Day';

import moment from 'moment';
import styles from './styles';

const DEVICE_WIDTH = Dimensions.get('window').width;
const VIEW_INDEX = 2;

export default class Calendar extends Component {

  state = {
    selectedMoment: moment(this.props.selectedDate),
    currentMonthMoment: moment(this.props.startDate),
  };

  static defaultProps = {
    scrollEnabled: false,
    showControls: false,
    prevButtonText: 'Prev',
    nextButtonText: 'Next',
    titleFormat: 'MMMM YYYY',
    dayHeadings: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'],
    startDate: moment().format('YYYY-MM-DD'),
    eventDates: [],
    customStyle: {},
    weekStart: 1,
    today: moment(),
  };

  static propTypes = {
    onDateSelect: PropTypes.func,
    scrollEnabled: PropTypes.bool,
    showControls: PropTypes.bool,
    prevButtonText: PropTypes.string,
    nextButtonText: PropTypes.string,
    titleFormat: PropTypes.string,
    onSwipeNext: PropTypes.func,
    onSwipePrev: PropTypes.func,
    onTouchNext: PropTypes.func,
    onTouchPrev: PropTypes.func,
    // all Date types can be anything that moment.js can parse to a proper moment.
    // Most common cases are: Date object, date string, Moment object.
    startDate: PropTypes.any,
    selectedDate: PropTypes.any,
    // defaults to, well, today. The moment of rendering.
    today: PropTypes.any,
    eventDates: PropTypes.array, // array of anythng date-like, see comment above
    customStyle: PropTypes.object,
    // 0 - Sunday, 1 - Monday, 2 - Tuesday, etc (typically 0 or 1)
    weekStart: PropTypes.number,
    // array of weekday labels, starting with Sunday
    dayHeadings: PropTypes.array,
    // array of 12 month names, defaults to English
    monthNames: PropTypes.array,
  };

  componentDidMount() {
    this.scrollToItem(VIEW_INDEX);
  }

  componentDidUpdate() {
    this.scrollToItem(VIEW_INDEX);
  }

  getMonthStack(currentMonth) {
    if (this.props.scrollEnabled) {
      const res = [];
      for (let i = -VIEW_INDEX; i <= VIEW_INDEX; i++) {
        res.push(moment(currentMonth).add(i, 'month'));
      }
      return res;
    }
    return [moment(currentMonth)];
  }

 prepareEventDates(eventDates) {
    const parsedDates = {};

    eventDates.forEach(event => {
      const date = moment(event);
      const month = moment(date).startOf('month').format();
      if (!parsedDates[month]) {
        parsedDates[month] = {};
      }
      parsedDates[month][date.date() - 1] = true;
    })
    return parsedDates;
  }

  selectDate(date) {
    this.setState({
      selectedMoment: date,
    });
    this.props.onDateSelect && this.props.onDateSelect(date.format()); // eslint-disable-line no-unused-expressions, max-len
  }

  onPrev = () => {
    const newMoment = moment(this.state.currentMonthMoment).subtract(1, 'month');
    this.setState({ currentMonthMoment: newMoment });
    this.props.onTouchPrev && this.props.onTouchPrev(newMoment); // eslint-disable-line no-unused-expressions, max-len
  }

  onNext = () => {
    const newMoment = moment(this.state.currentMonthMoment).add(1, 'month');
    this.setState({ currentMonthMoment: newMoment });
    this.props.onTouchNext && this.props.onTouchNext(newMoment); // eslint-disable-line no-unused-expressions, max-len
  }

  scrollToItem(itemIndex) {
    const scrollToX = itemIndex * DEVICE_WIDTH;
    if (this.props.scrollEnabled) {
      this._calendar.scrollTo({ y: 0, x: scrollToX, animated: false });
    }
  }

  scrollEnded(event) {
    const position = event.nativeEvent.contentOffset.x;
    const currentPage = position / DEVICE_WIDTH;
    const newMoment = moment(this.state.currentMonthMoment).add(currentPage - VIEW_INDEX, 'month');
    this.setState({ currentMonthMoment: newMoment });

    if (currentPage < VIEW_INDEX) {
      this.props.onSwipePrev && this.props.onSwipePrev();
    } else if (currentPage > VIEW_INDEX) {
      this.props.onSwipeNext && this.props.onSwipeNext();
    }
  }

  renderMonthView(argMoment, eventDatesMap) {
    /*
      In the code bellow. several moments and datatypes are mentioned. To avoid confusion,
      here is the naming convention I used:

      Moments:
        arg - (any) date in a month we want to render
        today - day rendered as today. typically the moment of rendering
        selected moment

      Data types:
        moment - moment.js object
        index - 0, 1, 2, .. :) Typically index of day within a given month
    */

    let // eslint-disable-line one-var
      renderIndex = 0,
      weekRows = [],
      days = [],
      startOfArgMonthMoment = argMoment.startOf('month');

    const // eslint-disable-line one-var
      selectedMoment = moment(this.state.selectedMoment),
      weekStart = this.props.weekStart,
      todayMoment = moment(this.props.today),
      todayIndex = todayMoment.date() - 1,
      argMonthDaysCount = argMoment.daysInMonth(),
      offset = (startOfArgMonthMoment.isoWeekday() - weekStart + 7) % 7,
      argMonthIsToday = argMoment.isSame(todayMoment, 'month'),
      selectedIndex = moment(selectedMoment).date() - 1,
      selectedMonthIsArg = selectedMoment.isSame(argMoment, 'month');

    const events = (eventDatesMap !== null)
      ? eventDatesMap[argMoment.startOf('month').format()]
      : null;

    // let before = (new Date()).getTime()

    for (;;) {
      const dayIndex = renderIndex - offset;
      const isoWeekday = (renderIndex + weekStart) % 7;

      if (dayIndex >= 0 && dayIndex < argMonthDaysCount) {
        days.push((
          <Day
            startOfMonth={startOfArgMonthMoment}
            isWeekend={isoWeekday === 0 || isoWeekday === 6}
            key={`${renderIndex}`}
            onPress={() => {
              this.selectDate(moment(startOfArgMonthMoment).set('date', dayIndex + 1));
            }}
            caption={`${dayIndex + 1}`}
            isToday={argMonthIsToday && (dayIndex === todayIndex)}
            isSelected={selectedMonthIsArg && (dayIndex === selectedIndex)}
            hasEvent={events && events[dayIndex] === true}
            usingEvents={this.props.eventDates.length > 0}
            customStyle={this.props.customStyle}
          />
        ));
      } else {
        days.push(<Day key={`${renderIndex}`} filler />);
      }
      if (renderIndex % 7 === 6) {
        weekRows.push(
          <View
            key={weekRows.length}
            style={[styles.weekRow, this.props.customStyle.weekRow]}
          >
              {days}
          </View>);
        days = [];
        if (dayIndex + 1 >= argMonthDaysCount) {
          break;
        }
      }
      renderIndex += 1;
    }

    // let after = (new Date()).getTime()
    // console.log('--- render time ---', after - before)
    return <View key={argMoment.month()} style={styles.monthContainer}>{weekRows}</View>;
  }

  renderHeading() {
    const headings = [];
    for (let i = 0; i < 7; i++) {
      const j = (i + this.props.weekStart) % 7;
      headings.push(
        <Text
          key={i}
          style={j === 0 || j === 6 ?
            [styles.weekendHeading, this.props.customStyle.weekendHeading] :
            [styles.dayHeading, this.props.customStyle.dayHeading]}
        >
          {this.props.dayHeadings[j]}
        </Text>
      );
    }

    return (
      <View style={[styles.calendarHeading, this.props.customStyle.calendarHeading]}>
        {headings}
      </View>
    );
  }

  renderTopBar() {
    let localizedMonth = this.props.monthNames[this.state.currentMonthMoment.month()];
    return this.props.showControls
    ? (
        <View style={[styles.calendarControls, this.props.customStyle.calendarControls]}>
          <TouchableOpacity
            style={[styles.controlButton, this.props.customStyle.controlButton]}
            onPress={this.onPrev}
          >
            <Text style={[styles.controlButtonText, this.props.customStyle.controlButtonText]}>
              {this.props.prevButtonText}
            </Text>
          </TouchableOpacity>
          <Text style={[styles.title, this.props.customStyle.title]}>
            {localizedMonth} {this.state.currentMonthMoment.year()}
          </Text>
          <TouchableOpacity
            style={[styles.controlButton, this.props.customStyle.controlButton]}
            onPress={this.onNext}
          >
            <Text style={[styles.controlButtonText, this.props.customStyle.controlButtonText]}>
              {this.props.nextButtonText}
            </Text>
          </TouchableOpacity>
        </View>
      )
    : (
      <View style={[styles.calendarControls, this.props.customStyle.calendarControls]}>
        <Text style={[styles.title, this.props.customStyle.title]}>
          {this.state.currentMonthMoment.format(this.props.titleFormat)}
        </Text>
      </View>
    );
  }

  render() {
    console.log('Rendering')
    const calendarDates = this.getMonthStack(this.state.currentMonthMoment);
    const eventDatesMap = this.prepareEventDates(this.props.eventDates);
    return (
      <View style={[styles.calendarContainer, this.props.customStyle.calendarContainer]}>
        {this.renderTopBar()}
        {this.renderHeading(this.props.titleFormat)}
        {this.props.scrollEnabled ?
          <ScrollView
            ref={calendar => this._calendar = calendar}
            horizontal
            scrollEnabled
            pagingEnabled
            removeClippedSubviews
            scrollEventThrottle={1000}
            showsHorizontalScrollIndicator={false}
            automaticallyAdjustContentInsets
            onMomentumScrollEnd={(event) => this.scrollEnded(event)}
          >
            {calendarDates.map((date) => this.renderMonthView(moment(date), eventDatesMap))}
          </ScrollView>
          :
          <View ref={calendar => this._calendar = calendar}>
            {calendarDates.map((date) => this.renderMonthView(moment(date), eventDatesMap))}
          </View>
        }
      </View>
    );
  }
}
<commit_msg>[Calendar] General cleanup<commit_after>import React, { Component, PropTypes } from 'react';
import {
  Dimensions,
  ScrollView,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

import Day from './Day';

import moment from 'moment';
import styles from './styles';

const DEVICE_WIDTH = Dimensions.get('window').width;
const VIEW_INDEX = 2;

export default class Calendar extends Component {

  state = {
    selectedMoment: moment(this.props.selectedDate),
    currentMonthMoment: moment(this.props.startDate),
  };

  static defaultProps = {
    scrollEnabled: false,
    showControls: false,
    prevButtonText: 'Prev',
    nextButtonText: 'Next',
    titleFormat: 'MMMM YYYY',
    dayHeadings: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'],
    startDate: moment().format('YYYY-MM-DD'),
    eventDates: [],
    customStyle: {},
    weekStart: 1,
    today: moment(),
  };

  static propTypes = {
    onDateSelect: PropTypes.func,
    scrollEnabled: PropTypes.bool,
    showControls: PropTypes.bool,
    prevButtonText: PropTypes.string,
    nextButtonText: PropTypes.string,
    titleFormat: PropTypes.string,
    onSwipeNext: PropTypes.func,
    onSwipePrev: PropTypes.func,
    onTouchNext: PropTypes.func,
    onTouchPrev: PropTypes.func,
    // all Date types can be anything that moment.js can parse to a proper moment.
    // Most common cases are: Date object, date string, Moment object.
    startDate: PropTypes.any,
    selectedDate: PropTypes.any,
    // defaults to, well, today. The moment of rendering.
    today: PropTypes.any,
    eventDates: PropTypes.array, // array of anythng date-like, see comment above
    customStyle: PropTypes.object,
    // 0 - Sunday, 1 - Monday, 2 - Tuesday, etc (typically 0 or 1)
    weekStart: PropTypes.number,
    // array of weekday labels, starting with Sunday
    dayHeadings: PropTypes.array,
    // array of 12 month names, defaults to English
    monthNames: PropTypes.array,
  };

  componentDidMount() {
    this.scrollToItem(VIEW_INDEX);
  }

  componentDidUpdate() {
    this.scrollToItem(VIEW_INDEX);
  }

  getMonthStack(currentMonth) {
    if (this.props.scrollEnabled) {
      const res = [];
      for (let i = -VIEW_INDEX; i <= VIEW_INDEX; i++) {
        res.push(moment(currentMonth).add(i, 'month'));
      }
      return res;
    }
    return [moment(currentMonth)];
  }

 prepareEventDates(eventDates) {
    const parsedDates = {};

    eventDates.forEach(event => {
      const date = moment(event);
      const month = moment(date).startOf('month').format();
      if (!parsedDates[month]) {
        parsedDates[month] = {};
      }
      parsedDates[month][date.date() - 1] = true;
    })
    return parsedDates;
  }

  selectDate(date) {
    this.setState({
      selectedMoment: date,
    });
    this.props.onDateSelect && this.props.onDateSelect(date.format()); // eslint-disable-line no-unused-expressions, max-len
  }

  onPrev = () => {
    const newMoment = moment(this.state.currentMonthMoment).subtract(1, 'month');
    this.setState({ currentMonthMoment: newMoment });
    this.props.onTouchPrev && this.props.onTouchPrev(newMoment); // eslint-disable-line no-unused-expressions, max-len
  }

  onNext = () => {
    const newMoment = moment(this.state.currentMonthMoment).add(1, 'month');
    this.setState({ currentMonthMoment: newMoment });
    this.props.onTouchNext && this.props.onTouchNext(newMoment); // eslint-disable-line no-unused-expressions, max-len
  }

  scrollToItem(itemIndex) {
    const scrollToX = itemIndex * DEVICE_WIDTH;
    if (this.props.scrollEnabled) {
      this._calendar.scrollTo({ y: 0, x: scrollToX, animated: false });
    }
  }

  scrollEnded(event) {
    const position = event.nativeEvent.contentOffset.x;
    const currentPage = position / DEVICE_WIDTH;
    const newMoment = moment(this.state.currentMonthMoment).add(currentPage - VIEW_INDEX, 'month');
    this.setState({ currentMonthMoment: newMoment });

    if (currentPage < VIEW_INDEX) {
      this.props.onSwipePrev && this.props.onSwipePrev();
    } else if (currentPage > VIEW_INDEX) {
      this.props.onSwipeNext && this.props.onSwipeNext();
    }
  }

  renderMonthView(argMoment, eventDatesMap) {

    let
      days = [],
      renderIndex = 0,
      startOfArgMonthMoment = argMoment.startOf('month');
      weekRows = [],

    const
      selectedMoment = moment(this.state.selectedMoment),
      weekStart = this.props.weekStart,
      todayMoment = moment(this.props.today),
      todayIndex = todayMoment.date() - 1,
      argMonthDaysCount = argMoment.daysInMonth(),
      offset = (startOfArgMonthMoment.isoWeekday() - weekStart + 7) % 7,
      argMonthIsToday = argMoment.isSame(todayMoment, 'month'),
      selectedIndex = moment(selectedMoment).date() - 1,
      selectedMonthIsArg = selectedMoment.isSame(argMoment, 'month');

    const events = (eventDatesMap !== null)
      ? eventDatesMap[argMoment.startOf('month').format()]
      : null;

    do {
      const dayIndex = renderIndex - offset;
      const isoWeekday = (renderIndex + weekStart) % 7;

      if (dayIndex >= 0 && dayIndex < argMonthDaysCount) {
        days.push((
          <Day
            startOfMonth={startOfArgMonthMoment}
            isWeekend={isoWeekday === 0 || isoWeekday === 6}
            key={`${renderIndex}`}
            onPress={() => {
              this.selectDate(moment(startOfArgMonthMoment).set('date', dayIndex + 1));
            }}
            caption={`${dayIndex + 1}`}
            isToday={argMonthIsToday && (dayIndex === todayIndex)}
            isSelected={selectedMonthIsArg && (dayIndex === selectedIndex)}
            hasEvent={events && events[dayIndex] === true}
            usingEvents={this.props.eventDates.length > 0}
            customStyle={this.props.customStyle}
          />
        ));
      } else {
        days.push(<Day key={`${renderIndex}`} filler />);
      }
      if (renderIndex % 7 === 6) {
        weekRows.push(
          <View
            key={weekRows.length}
            style={[styles.weekRow, this.props.customStyle.weekRow]}
          >
            {days}
          </View>);
        days = [];
        if (dayIndex + 1 >= argMonthDaysCount) {
          break;
        }
      }
      renderIndex += 1;
    } while (true)

    return <View key={argMoment.month()} style={styles.monthContainer}>{weekRows}</View>;
  }

  renderHeading() {
    const headings = [];
    for (let i = 0; i < 7; i++) {
      const j = (i + this.props.weekStart) % 7;
      headings.push(
        <Text
          key={i}
          style={j === 0 || j === 6 ?
            [styles.weekendHeading, this.props.customStyle.weekendHeading] :
            [styles.dayHeading, this.props.customStyle.dayHeading]}
        >
          {this.props.dayHeadings[j]}
        </Text>
      );
    }

    return (
      <View style={[styles.calendarHeading, this.props.customStyle.calendarHeading]}>
        {headings}
      </View>
    );
  }

  renderTopBar() {
    let localizedMonth = this.props.monthNames[this.state.currentMonthMoment.month()];
    return this.props.showControls
    ? (
        <View style={[styles.calendarControls, this.props.customStyle.calendarControls]}>
          <TouchableOpacity
            style={[styles.controlButton, this.props.customStyle.controlButton]}
            onPress={this.onPrev}
          >
            <Text style={[styles.controlButtonText, this.props.customStyle.controlButtonText]}>
              {this.props.prevButtonText}
            </Text>
          </TouchableOpacity>
          <Text style={[styles.title, this.props.customStyle.title]}>
            {localizedMonth} {this.state.currentMonthMoment.year()}
          </Text>
          <TouchableOpacity
            style={[styles.controlButton, this.props.customStyle.controlButton]}
            onPress={this.onNext}
          >
            <Text style={[styles.controlButtonText, this.props.customStyle.controlButtonText]}>
              {this.props.nextButtonText}
            </Text>
          </TouchableOpacity>
        </View>
      )
    : (
      <View style={[styles.calendarControls, this.props.customStyle.calendarControls]}>
        <Text style={[styles.title, this.props.customStyle.title]}>
          {this.state.currentMonthMoment.format(this.props.titleFormat)}
        </Text>
      </View>
    );
  }

  render() {
    console.log('Rendering')
    const calendarDates = this.getMonthStack(this.state.currentMonthMoment);
    const eventDatesMap = this.prepareEventDates(this.props.eventDates);
    return (
      <View style={[styles.calendarContainer, this.props.customStyle.calendarContainer]}>
        {this.renderTopBar()}
        {this.renderHeading(this.props.titleFormat)}
        {this.props.scrollEnabled ?
          <ScrollView
            ref={calendar => this._calendar = calendar}
            horizontal
            scrollEnabled
            pagingEnabled
            removeClippedSubviews
            scrollEventThrottle={1000}
            showsHorizontalScrollIndicator={false}
            automaticallyAdjustContentInsets
            onMomentumScrollEnd={(event) => this.scrollEnded(event)}
          >
            {calendarDates.map((date) => this.renderMonthView(moment(date), eventDatesMap))}
          </ScrollView>
          :
          <View ref={calendar => this._calendar = calendar}>
            {calendarDates.map((date) => this.renderMonthView(moment(date), eventDatesMap))}
          </View>
        }
      </View>
    );
  }
}
<|endoftext|>


<commit_before>import React,{ Component } from 'react';
import { inject, observer } from 'mobx-react';
import { SingleProduct } from '../components';

@inject('productStore') @observer
class Products extends Component {

  getProductId = (id) => {
    console.log(id);
  }

  render() {
    const {
      productStore: {
        products,
        error,
      },
    } = this.props;
    return (

        {products.map((product, idx) => (
          <SingleProduct
            {...product}
            key={product.id}
            getProductId={this.getProductId}
          />
        ))}

    );
  }
}

export default Products;
<commit_msg>call getProduct from component<commit_after>import React,{ Component } from 'react';
import { inject, observer } from 'mobx-react';
import { SingleProduct } from '../components';

@inject('productStore') @observer
class Products extends Component {

  getProductId = (id) => {
    const { productStore: { getSingleProduct } } = this.props;
    getSingleProduct(id)
    .then(product => console.log(product));
  }

  render() {
    const {
      productStore: {
        products,
        error,
      },
    } = this.props;
    return (

        {products.map((product, idx) => (
          <SingleProduct
            {...product}
            key={product.id}
            getProductId={this.getProductId}
          />
        ))}

    );
  }
}

export default Products;
<|endoftext|>


<commit_before>define([
  'backbone', 'underscore', 'handlebars', 'moment',
  'map/models/UserModel',
  'map/presenters/tabs/SubscribePresenter',
  'connect/models/Subscription',
  'text!map/templates/tabs/subscribe.handlebars'
], function(Backbone, _, Handlebars, moment, User, Presenter, Subscription, tpl) {

  'use strict';

  var TOPICS = {
    loss: 'alerts/treeloss',
    forestgain: 'alerts/treegain',
    forma: 'alerts/forma',
    imazon: 'alerts/sad',
    modis: 'alerts/quicc',
    terrailoss: 'alerts/terra',
    prodes: 'alerts/prodes',
    guyra: 'alerts/guyra'
  };

  var SubscribeView = Backbone.View.extend({

    id: 'subscription-modal',
    className: 'subscription-modal',

    template: Handlebars.compile(tpl),

    events: {
      'click .subscription-modal-close': 'close',
      'click .subscription-modal-backdrop': 'close',
      'click #returnToMap': 'close',
      'click #showName': 'askForName',
      'click #subscribe': 'subscribe',
    },

    initialize: function(){
      this.presenter = new Presenter(this);

      this.user = new User();
      this.listenTo(this.user, 'sync', this.render);
      this.user.fetch();

      this.render();
    },

    render: function(){
      this.$el.html(this.template({
        email: this.user.get('email'),
        loggedIn: this.user.isLoggedIn(),
        date: moment().format('MMM D, YYYY')
      }));
      this.setupAuthLinks();

      return this;
    },

    show: function(options){
      if (this.user.get('id') && _.isEmpty(this.user.get('email'))) {
        this.showSpinner();
        this.user.fetch();
      }

      this.createSubscription(options);
      this.currentStep = 0;

      this.$el.addClass('is-active');
    },

    close: function(event) {
      if (event !== undefined && event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
      }

      this.$el.removeClass('is-active');
      this.render();
      this.presenter.updateUrl();
    },

    showSpinner: function() {
      this.$('.subscription-spinner-container').css('visibility', 'visible');
    },

    hideSpinner: function() {
      this.$('.subscription-spinner-container').css('visibility', 'hidden');
    },

    setupAuthLinks: function() {
      var apiHost = window.gfw.config.GFW_API_HOST;

      this.$('.subscription-sign-in').each(function() {
        var $link = $(this);
        $link.attr('href', apiHost + $link.attr('href'));
      });
    },

    createSubscription: function(options) {
      var analysisResource = options.analysisResource,
          geostoreId = options.geostore;

      this.subscription = new Subscription({
        topic: TOPICS[options.layer.slug] || options.layer.title,
        url: window.location.href
      });
      this.subscription.set(analysisResource);

      if (analysisResource) {
        var geom;
        if (analysisResource.type === 'geojson') {
          geom = JSON.parse(analysisResource.geojson);
        } else {
          if (analysisResource.geom) {
            geom = analysisResource.geom.geometry;
          } else {
            geom = this.presenter.geom_for_subscription;
          }
        }
        this.subscription.set('geom', geom);
      } else if (geostoreId) {
        this.subscription.set('geostore_id', geostoreId);
      }
    },

    askForName: function() {
      this.subscription.set('email',
        this.$el.find('#subscriptionEmail').val());

      if (this.subscription.hasValidEmail()) {
        this.nextStep();
      } else {
        this.presenter.notificate('email-incorrect');
      }
    },

    subscribe: function() {
      this.showSpinner();

      window.ga('send', 'event', 'Map', 'Subscribe', 'Layer: ' +
        this.subscription.get('topic') + ', Email: ' + this.subscription.get('email'));

      this.subscription.set('name',
        this.$el.find('#subscriptionName').val());

      this.subscription.save().
        then(this.onSave.bind(this)).
        fail(this.close.bind(this));
    },

    onSave: function() {
      this.hideSpinner();
      this.presenter.subscribeEnd();
      this.nextStep();
    },

    nextStep: function(index) {
      if (this.currentStep === undefined) {
        this.currentStep = 0;
      }

      if (index !== undefined && _.isNumber(index)) {
        this.currentStep = index;
      } else {
        this.currentStep += 1;
      }

      var $steps = this.$('.steps');
      $steps.removeClass('current');
      $steps.eq(this.currentStep).addClass('current');
    }

  });

  return SubscribeView;
});
<commit_msg>Add topic mapping for GLAD layer<commit_after>define([
  'backbone', 'underscore', 'handlebars', 'moment',
  'map/models/UserModel',
  'map/presenters/tabs/SubscribePresenter',
  'connect/models/Subscription',
  'text!map/templates/tabs/subscribe.handlebars'
], function(Backbone, _, Handlebars, moment, User, Presenter, Subscription, tpl) {

  'use strict';

  var TOPICS = {
    loss: 'alerts/treeloss',
    forestgain: 'alerts/treegain',
    forma: 'alerts/forma',
    imazon: 'alerts/sad',
    modis: 'alerts/quicc',
    terrailoss: 'alerts/terra',
    prodes: 'alerts/prodes',
    guyra: 'alerts/guyra',
    umd_as_it_happens: 'alerts/glad'
  };

  var SubscribeView = Backbone.View.extend({

    id: 'subscription-modal',
    className: 'subscription-modal',

    template: Handlebars.compile(tpl),

    events: {
      'click .subscription-modal-close': 'close',
      'click .subscription-modal-backdrop': 'close',
      'click #returnToMap': 'close',
      'click #showName': 'askForName',
      'click #subscribe': 'subscribe',
    },

    initialize: function(){
      this.presenter = new Presenter(this);

      this.user = new User();
      this.listenTo(this.user, 'sync', this.render);
      this.user.fetch();

      this.render();
    },

    render: function(){
      this.$el.html(this.template({
        email: this.user.get('email'),
        loggedIn: this.user.isLoggedIn(),
        date: moment().format('MMM D, YYYY')
      }));
      this.setupAuthLinks();

      return this;
    },

    show: function(options){
      if (this.user.get('id') && _.isEmpty(this.user.get('email'))) {
        this.showSpinner();
        this.user.fetch();
      }

      this.createSubscription(options);
      this.currentStep = 0;

      this.$el.addClass('is-active');
    },

    close: function(event) {
      if (event !== undefined && event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
      }

      this.$el.removeClass('is-active');
      this.render();
      this.presenter.updateUrl();
    },

    showSpinner: function() {
      this.$('.subscription-spinner-container').css('visibility', 'visible');
    },

    hideSpinner: function() {
      this.$('.subscription-spinner-container').css('visibility', 'hidden');
    },

    setupAuthLinks: function() {
      var apiHost = window.gfw.config.GFW_API_HOST;

      this.$('.subscription-sign-in').each(function() {
        var $link = $(this);
        $link.attr('href', apiHost + $link.attr('href'));
      });
    },

    createSubscription: function(options) {
      var analysisResource = options.analysisResource,
          geostoreId = options.geostore;

      this.subscription = new Subscription({
        topic: TOPICS[options.layer.slug] || options.layer.title,
        url: window.location.href
      });
      this.subscription.set(analysisResource);

      if (analysisResource) {
        var geom;
        if (analysisResource.type === 'geojson') {
          geom = JSON.parse(analysisResource.geojson);
        } else {
          if (analysisResource.geom) {
            geom = analysisResource.geom.geometry;
          } else {
            geom = this.presenter.geom_for_subscription;
          }
        }
        this.subscription.set('geom', geom);
      } else if (geostoreId) {
        this.subscription.set('geostore_id', geostoreId);
      }
    },

    askForName: function() {
      this.subscription.set('email',
        this.$el.find('#subscriptionEmail').val());

      if (this.subscription.hasValidEmail()) {
        this.nextStep();
      } else {
        this.presenter.notificate('email-incorrect');
      }
    },

    subscribe: function() {
      this.showSpinner();

      window.ga('send', 'event', 'Map', 'Subscribe', 'Layer: ' +
        this.subscription.get('topic') + ', Email: ' + this.subscription.get('email'));

      this.subscription.set('name',
        this.$el.find('#subscriptionName').val());

      this.subscription.save().
        then(this.onSave.bind(this)).
        fail(this.close.bind(this));
    },

    onSave: function() {
      this.hideSpinner();
      this.presenter.subscribeEnd();
      this.nextStep();
    },

    nextStep: function(index) {
      if (this.currentStep === undefined) {
        this.currentStep = 0;
      }

      if (index !== undefined && _.isNumber(index)) {
        this.currentStep = index;
      } else {
        this.currentStep += 1;
      }

      var $steps = this.$('.steps');
      $steps.removeClass('current');
      $steps.eq(this.currentStep).addClass('current');
    }

  });

  return SubscribeView;
});
<|endoftext|>


<commit_before>const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const commonConfig = require('./webpack.common');
const { ENV, dir, APP_VERSION } = require('./helpers');
const { CheckerPlugin } = require('awesome-typescript-loader');
// const ngtools = require('@ngtools/webpack');

const banner =
`/**
 * angular2-data-table v${APP_VERSION} (https://github.com/swimlane/angular2-data-table)
 * Copyright 2016
 * Licensed under MIT
 */`;

module.exports = function(env) {
  return webpackMerge(commonConfig({ env: ENV }), {
    devtool: 'source-map',
    module: {
      exprContextCritical: false,
      rules: [
        {
          test: /\.ts$/,
          loaders: [
            'awesome-typescript-loader',
            'angular2-template-loader'
          ],
          exclude: [/\.(spec|e2e|d)\.ts$/]
        }
      ]
    },
    entry: {
      'index': './src/index.ts'
    },
    output: {
      path: dir('release'),
      libraryTarget: 'umd',
      library: 'ngxDatatable',
      umdNamedDefine: true
    },
    externals: {
      '@angular/platform-browser-dynamic': '@angular/platform-browser-dynamic',
      '@angular/platform-browser': '@angular/platform-browser',
      '@angular/core': '@angular/core',
      '@angular/common': '@angular/common',
      '@angular/forms': '@angular/forms',
      'core-js': 'core-js',
      'core-js/es6': 'core-js/es6',
      'core-js/es7/reflect': 'core-js/es7/reflect',
      'rxjs': 'rxjs',
      'rxjs/Rx': 'rxjs/Rx',
      'rxjs/Subscription': 'rxjs/Subscription',
      'zone.js/dist/zone': 'zone.js/dist/zone'
    },
    plugins: [
      new webpack.optimize.ModuleConcatenationPlugin(),
      new CheckerPlugin(),
      new webpack.BannerPlugin({
        banner: banner,
        raw: true,
        entryOnly: true
      }),
      /*
      new ngtools.AotPlugin({
        tsConfigPath: 'tsconfig-aot.json',
        baseDir: dir()
        entryModule: dir('datatable.module.ts') + '#Angular2DataTableModule'
      }),
      new CleanWebpackPlugin(['release'], {
        root: dir(),
        verbose: false,
        dry: false
      })
      */
    ]
  });

};
<commit_msg>fix: build including rxjs<commit_after>const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const commonConfig = require('./webpack.common');
const { ENV, dir, APP_VERSION } = require('./helpers');
const { CheckerPlugin } = require('awesome-typescript-loader');
// const ngtools = require('@ngtools/webpack');

const banner =
`/**
 * angular2-data-table v${APP_VERSION} (https://github.com/swimlane/angular2-data-table)
 * Copyright 2016
 * Licensed under MIT
 */`;

module.exports = function(env) {
  return webpackMerge(commonConfig({ env: ENV }), {
    devtool: 'source-map',
    module: {
      exprContextCritical: false,
      rules: [
        {
          test: /\.ts$/,
          loaders: [
            'awesome-typescript-loader',
            'angular2-template-loader'
          ],
          exclude: [/\.(spec|e2e|d)\.ts$/]
        }
      ]
    },
    entry: {
      'index': './src/index.ts'
    },
    output: {
      path: dir('release'),
      libraryTarget: 'umd',
      library: 'ngxDatatable',
      umdNamedDefine: true
    },
    externals: {
      '@angular/platform-browser-dynamic': '@angular/platform-browser-dynamic',
      '@angular/platform-browser': '@angular/platform-browser',
      '@angular/core': '@angular/core',
      '@angular/common': '@angular/common',
      '@angular/forms': '@angular/forms',
      'core-js': 'core-js',
      'core-js/es6': 'core-js/es6',
      'core-js/es7/reflect': 'core-js/es7/reflect',
      'rxjs': 'rxjs',
      'rxjs/Rx': 'rxjs/Rx',
      'rxjs/Observable': 'rxjs/Observable',
      'rxjs/BehaviorSubject': 'rxjs/BehaviorSubject',
      'rxjs/observable/fromEvent': 'rxjs/observable/fromEvent',
      'rxjs/Subscription': 'rxjs/Subscription',
      'rxjs/operators': 'rxjs/operators',
      'zone.js/dist/zone': 'zone.js/dist/zone'
    },
    plugins: [
      new webpack.optimize.ModuleConcatenationPlugin(),
      new CheckerPlugin(),
      new webpack.BannerPlugin({
        banner: banner,
        raw: true,
        entryOnly: true
      }),
      /*
      new ngtools.AotPlugin({
        tsConfigPath: 'tsconfig-aot.json',
        baseDir: dir()
        entryModule: dir('datatable.module.ts') + '#Angular2DataTableModule'
      }),
      new CleanWebpackPlugin(['release'], {
        root: dir(),
        verbose: false,
        dry: false
      })
      */
    ]
  });

};
<|endoftext|>


<commit_before>var _onclick = on("click");
var preventClick = false, saved_x, saved_y, lasttime_click;
var needFireClick = false;
function clickstart(event) {
    saved_x = event.clientX, saved_y = event.clientY;
    needFireClick = true;
    onclick.preventClick = preventClick = false;
}
function clickcancel(event) {
    var abs = Math.abs;
    if (abs(event.clientX - saved_x) >= MOVELOCK_DELTA || abs(event.clientY - saved_y) >= MOVELOCK_DELTA)
        onclick.preventClick = preventClick = true;
}
onmousedown(window, clickstart);
onmousemove(window, clickcancel);
ontouchstart(window, function (event) {
    extendTouchEvent(event);
    clickstart.call(this, event);
});
ontouchmove(window, function (event) {
    extendTouchEvent(event);
    clickcancel.call(this, event);
});
if (window.addEventListener) {
    window.addEventListener("touchend", function (event) {
        var target = event.target;
        var touch = event.changedTouches[0];
        var clickEvent = document.createEvent("MouseEvents");
        clickEvent.initMouseEvent("click", true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
        dispatch(target, clickEvent);
    }, true);
    window.addEventListener("click", function (event) {
        if (!needFireClick) return;
        needFireClick = false;
        var saved_time = lasttime_click;
        lasttime_click = event.timeStamp;
        if (lasttime_click - saved_time < 60 || preventClick) {
            // 阻止非人为点击，防止误操作
            event.preventDefault();
            event.stopPropagation();
            return;
        }
    }, true);
}
var onclick = _onclick;<commit_msg>支持从外部设置preventClick<commit_after>var _onclick = on("click");
var saved_x, saved_y, lasttime_click;
var needFireClick = false;
function clickstart(event) {
    saved_x = event.clientX, saved_y = event.clientY;
    needFireClick = true;
    onclick.preventClick = false;
}
function clickcancel(event) {
    var abs = Math.abs;
    if (abs(event.clientX - saved_x) >= MOVELOCK_DELTA || abs(event.clientY - saved_y) >= MOVELOCK_DELTA)
        onclick.preventClick = true;
}
onmousedown(window, clickstart);
onmousemove(window, clickcancel);
ontouchstart(window, function (event) {
    extendTouchEvent(event);
    clickstart.call(this, event);
});
ontouchmove(window, function (event) {
    extendTouchEvent(event);
    clickcancel.call(this, event);
});
if (window.addEventListener) {
    window.addEventListener("touchend", function (event) {
        var target = event.target;
        var touch = event.changedTouches[0];
        var clickEvent = document.createEvent("MouseEvents");
        clickEvent.initMouseEvent("click", true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
        dispatch(target, clickEvent);
    }, true);
    window.addEventListener("click", function (event) {
        if (!needFireClick) return;
        needFireClick = false;
        var saved_time = lasttime_click;
        lasttime_click = event.timeStamp;
        if (lasttime_click - saved_time < 60 || onclick.preventClick) {
            // 阻止非人为点击，防止误操作
            event.preventDefault();
            event.stopPropagation();
            return;
        }
    }, true);
}
var onclick = _onclick;<|endoftext|>


<commit_before>
/**
 * Add terminal colors
 */

require('terminal-colors');

/**
 * Program configs
 */

module.exports = {

  // Folders
  LOCALES_FOLDER : 'locales',

  // Files
  DELETE_LOG_FILE     : '/delete.log',
  LATEST_SEARCH_CACHE : '/cache/latestSearch.json',

  // Gt log length
  LOG_LENGTH : 10,

  // Default values
  DEFAULT_TRANSLATION_FUNCTION : 'gt',
  DEFAULT_REQUIREJS            : true,
  DEFAULT_FOLDER               : 'translations',
  DEFAULT_OUTPUT               : 'output',
  DEFAULT_PORT                 : 3001,
  DEFAULT_AUTO_OPEN            : true,
  DEFAULT_QUIET                : false,

  NO_TRANSLATION : 'NO TRANSLATION',

  TRANSLATION_ID_HASH_SECRET : 'gt',
  TRANSLATION_ID_CHAR_LENGTH : 8,

  DEFAULT_PROGAMMING_LANGUAGE : 'javascript',

  // Syntaxes
  SYNTAX_OPERAND         : /^(it\.)?\w+$/,
  SYNTAX_VARIABLE        : /^[a-zA-Z][a-zA-Z0-9]+$/,
  SYNTAX_VARIABLE_MARKUP : /\$\{[a-zA-Z0-9]+\}/g,

  // conditions
  CONDITIONS : ['if', 'else', 'else if'],
  CONDITION_IF     : 'if',
  CONDITION_ELSE   : 'else',
  CONDITION_ELSEIF : 'else if',

  ADDITIONAL_CONDITIONS : ['&&', '||'],
  ADDITIONAL_CONDITION_AND : '&&',
  ADDITIONAL_CONDITION_OR  : '||',

  OPERATORS : ['<', '<=', '==', '===', '>', '>='],

  INIT_INTRO :
  'This utility will walk you through creating a get-transltion project.\n' +
  'It only covers the most common items, and tries to guess sane defaults.\n' +
  '\n' +
  'Press ^C at any time to quit.\n\n',

  LOCALES_DESCRIPTION :
  'Please add at least one locale to your project.\n' +
  'The syntax should be a comma separated list of ' + 'LOCALE_CODE:LOCALE_NAME'.yellow + '\nformated strings.\n' +
  '\n' +
  '  Example:\n' +
  '\n' +
  '    en-US:English,zh-CN:Chinese\n\n',

  LOCALES_WRONG_ANSWER : '\nUnrecognized string. Please add your locales again.'.red + '\n\n',

  LOCALES_SYNTAX : /([\w\-]+:[\(\)\w\-\s]+,?)+/,

  DEFAULT_LOCALE_CODE : 'en-US',
  DEFAULT_LOCALE_NAME : 'English (US)',

  DEFAULT_LOCALE_QUESTION : '\nPlease choose your default locale:\n',

  DEFAULT_LOCALE_WRONG_ANSWER : '\nYour option didn\'t match any of the locales you provided.\n'.red,

  PROGRAMMING_LANGUAGUES : ['javascript'],

  CHOOSE_PROGRAMMING_LANGUAGE_PROMPT : 'Choose one of the following programming languagues:\n',
  CHOOSE_PROGRAMMING_LANGUAGE_WRONG_ANSWER : '\nUnrecognized programming language. Please try again.'.red + '\n\n',

  PROGRAMMING_LANGUAGUE_TO_DEFAULT_SRC_MAP : {
    'javascript' : [
      '!node_modules/**'
    ]
  },

  DEFAULT_CONFIGS : {
    quiet : false,
    interface : {
      autoOpenBrowser: false,
      port : 3000
    }
  },

  DEFAULT_OUTPUT_FOLDER_PROMPT :
  '\nAll translations will be compiled to a single folder.\n' +
  'Please specify which folder you want them to be compiled to.\n\n',

  DEFAULT_OUTPUT_FOLDER : 'l10n/',

  DEFAULT_OUTPUT_FOLDER_WRONG_ANSWER : '\nFailed to resolve path. Please try again.\n',

  PROJECT_ALREADY_INITIATED : 'Project already initiated'
};

<commit_msg>Removed node_modules folder from default source for javascript<commit_after>
/**
 * Add terminal colors
 */

require('terminal-colors');

/**
 * Program configs
 */

module.exports = {

  // Folders
  LOCALES_FOLDER : 'locales',

  // Files
  DELETE_LOG_FILE     : '/delete.log',
  LATEST_SEARCH_CACHE : '/cache/latestSearch.json',

  // Gt log length
  LOG_LENGTH : 10,

  // Default values
  DEFAULT_TRANSLATION_FUNCTION : 'gt',
  DEFAULT_REQUIREJS            : true,
  DEFAULT_FOLDER               : 'translations',
  DEFAULT_OUTPUT               : 'output',
  DEFAULT_PORT                 : 3001,
  DEFAULT_AUTO_OPEN            : true,
  DEFAULT_QUIET                : false,

  NO_TRANSLATION : 'NO TRANSLATION',

  TRANSLATION_ID_HASH_SECRET : 'gt',
  TRANSLATION_ID_CHAR_LENGTH : 8,

  DEFAULT_PROGAMMING_LANGUAGE : 'javascript',

  // Syntaxes
  SYNTAX_OPERAND         : /^(it\.)?\w+$/,
  SYNTAX_VARIABLE        : /^[a-zA-Z][a-zA-Z0-9]+$/,
  SYNTAX_VARIABLE_MARKUP : /\$\{[a-zA-Z0-9]+\}/g,

  // conditions
  CONDITIONS : ['if', 'else', 'else if'],
  CONDITION_IF     : 'if',
  CONDITION_ELSE   : 'else',
  CONDITION_ELSEIF : 'else if',

  ADDITIONAL_CONDITIONS : ['&&', '||'],
  ADDITIONAL_CONDITION_AND : '&&',
  ADDITIONAL_CONDITION_OR  : '||',

  OPERATORS : ['<', '<=', '==', '===', '>', '>='],

  INIT_INTRO :
  'This utility will walk you through creating a get-transltion project.\n' +
  'It only covers the most common items, and tries to guess sane defaults.\n' +
  '\n' +
  'Press ^C at any time to quit.\n\n',

  LOCALES_DESCRIPTION :
  'Please add at least one locale to your project.\n' +
  'The syntax should be a comma separated list of ' + 'LOCALE_CODE:LOCALE_NAME'.yellow + '\nformated strings.\n' +
  '\n' +
  '  Example:\n' +
  '\n' +
  '    en-US:English,zh-CN:Chinese\n\n',

  LOCALES_WRONG_ANSWER : '\nUnrecognized string. Please add your locales again.'.red + '\n\n',

  LOCALES_SYNTAX : /([\w\-]+:[\(\)\w\-\s]+,?)+/,

  DEFAULT_LOCALE_CODE : 'en-US',
  DEFAULT_LOCALE_NAME : 'English (US)',

  DEFAULT_LOCALE_QUESTION : '\nPlease choose your default locale:\n',

  DEFAULT_LOCALE_WRONG_ANSWER : '\nYour option didn\'t match any of the locales you provided.\n'.red,

  PROGRAMMING_LANGUAGUES : ['javascript'],

  CHOOSE_PROGRAMMING_LANGUAGE_PROMPT : 'Choose one of the following programming languagues:\n',
  CHOOSE_PROGRAMMING_LANGUAGE_WRONG_ANSWER : '\nUnrecognized programming language. Please try again.'.red + '\n\n',

  PROGRAMMING_LANGUAGUE_TO_DEFAULT_SRC_MAP : {
    'javascript' : []
  },

  DEFAULT_CONFIGS : {
    quiet : false,
    interface : {
      autoOpenBrowser: false,
      port : 3000
    }
  },

  DEFAULT_OUTPUT_FOLDER_PROMPT :
  '\nAll translations will be compiled to a single folder.\n' +
  'Please specify which folder you want them to be compiled to.\n\n',

  DEFAULT_OUTPUT_FOLDER : 'l10n/',

  DEFAULT_OUTPUT_FOLDER_WRONG_ANSWER : '\nFailed to resolve path. Please try again.\n',

  PROJECT_ALREADY_INITIATED : 'Project already initiated'
};

<|endoftext|>


<commit_before>var netutil = require("netutil");
var connect = require("connect");

module.exports = function startup(options, imports, register) {
    imports.log.info("connect plugin start");

    var server = connect();

    var hookNames = [
        "Start",
        "Setup",
        "Main",
        "Session",
        "Auth",
        "Error"
    ];
    var api = {
        getModule: function() {
            return connect;
        }
    };
    hookNames.forEach(function(name) {
        var hookServer = connect();
        server.use(hookServer);
        api["use" + name] = hookServer.use.bind(hookServer);
    });

    api.useSetup(connect.cookieParser());
    api.useSetup(connect.bodyParser());

    api.addRoute = server.addRoute;
    api.use = api.useStart;

    api.on = server.on;
    api.emit = server.emit;

    function startListening (port, host) {
        api.getPort = function () {
            return port;
        };
        api.getHost = function () {
            return host;
        };

        server.listen(port, host, function(err) {
            if (err)
                return register(err);

            imports.log.info("Connect server listening at http://" + host + ":" + port);

            register(null, {
                "onDestruct": function(callback) {
                    server.close();
                    server.on("close", callback);
                },
                "connect": api,
                "http": {
                    getServer: function() {
                        return server;
                    }
                }
            });
        });
    }

    if (options.port instanceof Array) {
        netutil.findFreePort(options.port[0], options.port[1], options.host, function(err, port) {
            if (err)
                return register(err);

            startListening(port, options.host);
        });
    } else {
        startListening(options.port, options.host);
    }
};<commit_msg>fix log message<commit_after>var netutil = require("netutil");
var connect = require("connect");

module.exports = function startup(options, imports, register) {
    imports.log.info("connect plugin start");

    var server = connect();

    var hookNames = [
        "Start",
        "Setup",
        "Main",
        "Session",
        "Auth",
        "Error"
    ];
    var api = {
        getModule: function() {
            return connect;
        }
    };
    hookNames.forEach(function(name) {
        var hookServer = connect();
        server.use(hookServer);
        api["use" + name] = hookServer.use.bind(hookServer);
    });

    api.useSetup(connect.cookieParser());
    api.useSetup(connect.bodyParser());

    api.addRoute = server.addRoute;
    api.use = api.useStart;

    api.on = server.on;
    api.emit = server.emit;

    function startListening (port, host) {
        api.getPort = function () {
            return port;
        };
        api.getHost = function () {
            return host;
        };

        server.listen(port, host, function(err) {
            if (err)
                return register(err);

            imports.log.info("Connect server listening at http://" + host + ":" + port);

            register(null, {
                "onDestruct": function(callback) {
                    server.close();
                    server.on("close", callback);
                },
                "connect": api,
                "http": {
                    getServer: function() {
                        return server;
                    }
                }
            });
        });
    }

    if (options.port instanceof Array) {
        netutil.findFreePort(options.port[0], options.port[1], options.host, function(err, port) {
            if (err)
                return register(err);

            startListening(port, options.host || "localhost");
        });
    } else {
        startListening(options.port, options.host);
    }
};<|endoftext|>