<commit_before>Accents.module("TermsApp.Views", function(Views, Accents, Backbone, Marionette, $, _){
  // form for adding terms
  Views.AddTermFormView = Backbone.Marionette.ItemView.extend({
    template: '#add-term-form-template',
    currentAlertView: null,
    events: {
         'click button': 'addTerm',
         'change #add-word': 'updateTerm',
         'keyup #add-word': 'updateTerm',
    },
    ui: {
        term: '#add-word',
        ref: '#book-ref',
        rendered_word: '#rendered-word',
    },

    onRender: function(){
      if(Accents.TermsApp.refValue){
        this.ui.ref.val( Accents.TermsApp.refValue );
      }
    },

    addTerm: function () {
       console.log('Adding new term: ', this.ui.term.val(), this.ui.ref.val());
       var self = this;
       if( this.currentAlertView ){
         this.currentAlertView.remove();
       }
       var validateTerm = new Accents.Entities.Term({
            term: this.ui.term.val(),
            ref: this.ui.ref.val(),
            user : Accents.user.get('user'),
       });
        var errors = validateTerm.validate();
        if( _.isEmpty(errors) ){
          var termValues = validateTerm.get("term").split(" ");
          _.each(termValues, function(termV){
              var savedModel = new Accents.Entities.Term({
                  id: Accents.Utils.genUUID('xxxxxxxxxx'),
                  term: termV,
                  ref: self.ui.ref.val(),
                  user : Accents.user.get('user'),
                  type: 'term'
              });
              self.collection.add(savedModel);
              savedModel.save({}, {
                  error: function(model, response) {
                      console.log(response.responseText);
                  }
              });
          });
          this.ui.term.val('');
          this.ui.ref.val('');
          this.ui.rendered_word.empty();
          this.ui.term.focus();
        }else{
          this.showErrors(errors);
	}
    },
    updateTerm: function (e) {
      if(e.keyCode == 13){
        this.addTerm();
      }else{
        var pos = this.ui.term[0].selectionStart;
        var term = this.ui.term.val();
        var part = Accents.Utils.renderGlyph2UTF(term.slice(0, pos));
        this.ui.term.val(part + term.slice(pos));
        this.ui.term[0].selectionStart = part.length;
        this.ui.term[0].selectionEnd = part.length;
        // temporarily display HTML version below since we cannot display underscores in input
        this.ui.rendered_word.html(Accents.Utils.renderTypedTerm(this.ui.term.val()));

        Accents.trigger("filter:terms", term);
      }
    },

    showErrors: function(errors){
      var _errors =[];
      if(errors.term){
        _errors.push("Term: " + errors.term);
      }
      if(errors.ref){
        _errors.push("Ref: " + errors.ref);
      }
      this.currentAlertView = new Views.AlertView( {model: new Backbone.Model({errors: _errors}) } );
      //this.$(".form-inline").prepend("
"+ _errors  +"
");
      this.$(".alert-container").html(this.currentAlertView.render().el);
      if( errors.term ){  this.ui.term.parent().addClass("has-error"); }
      if( errors.term ){  this.ui.ref.parent().addClass("has-error"); }
    }
  });

  // temporary add/remove links
  Views.TempLinksView = Backbone.Marionette.ItemView.extend({
    template: '#temp-links-template',
    events: {
         'click button#deleteall': 'deleteAll',
         'click button#generatefakes': 'generateFakes',
    },
    deleteAll: function() {
        while (model = this.collection.first()) {
            model.destroy();
        }
    },
    generateFakes: function () {
        Accents.Entities.fakeTerms(this.collection);
    },
  });

  // table of terms at bottom
  Views.TermView = Backbone.Marionette.ItemView.extend({
    template: '#term-list-item-template',
    tagName: 'tr',
    /*templateHelpers: {
        ilm2html: function() {
            return Accents.Utils.ilm2HTML(this.term);
        }
    }*/
  });

  Views.FilteredTermView = Backbone.Marionette.ItemView.extend({
    template: '#term-filtered-list-item-template',
    tagName: 'tr'
  });

  Views.TermsView = Backbone.Marionette.CompositeView.extend({
    template: '#terms-list-table-template',
    itemView: Views.TermView,
    itemViewContainer: 'tbody',
    collectionEvents: {
        "change reset add remove": "render"
    }
  });

  Views.FilteredTermsView = Backbone.Marionette.CompositeView.extend({
    template: '#terms-filtered-list-table-template',
    itemView: Views.FilteredTermView,
    itemViewContainer: 'tbody',
    collectionEvents: {
        "reset add remove": "render"
    },

    initialize: function(){
      var groupedObject = this.collection.countBy("term");
      var array = [];
      for(object in groupedObject ){
        array.push({term: object, count: groupedObject[object]});
      }
      this.collection = new Backbone.Collection(array);
      Accents.on("filter:terms", this.filterTerms);
    },

    filterTerms: function(term){
      console.log("Lets filter terms: " + term );
    }

  });

  // table of terms at bottom
  Views.TotalTermsView = Backbone.Marionette.ItemView.extend({
    template: '#term-list-total-template',
    serializeData: function() {
        return {
            "total_count": this.collection.length
        };
    },
    collectionEvents: {
        "change reset add remove": "render",
    },
    tagName: 'h3'
  });

  // add terms main area
  Views.AddTermMainLayout = Marionette.Layout.extend({
    template: '#add-term-main-layout-template',
    regions: {
      add_term_form : "#add-term-form",
      add_remove_links  : "#add-remove-links",
      add_terms_list  : "#add-terms-list",
    }
  });

  // table layout with total at the top
  Views.TermsListLayout = Marionette.Layout.extend({
    template: '#terms-list-layout-template',
    regions: {
      add_term_list_total: "#terms-total",
      add_term_list_table: "#terms-table",
      add_term_filtered_table: "#terms-filtered-table"
    }
  });

  Views.AlertView =  Backbone.Marionette.ItemView.extend({
    template: "#alert-template",

    events:{
      "click .close": "close"
    },

    close: function(e){
      this.remove();
    }
  });

});
<commit_msg>Filtered function was implemented<commit_after>Accents.module("TermsApp.Views", function(Views, Accents, Backbone, Marionette, $, _){
  // form for adding terms
  Views.AddTermFormView = Backbone.Marionette.ItemView.extend({
    template: '#add-term-form-template',
    currentAlertView: null,
    events: {
         'click button': 'addTerm',
         'change #add-word': 'updateTerm',
         'keyup #add-word': 'updateTerm',
    },
    ui: {
        term: '#add-word',
        ref: '#book-ref',
        rendered_word: '#rendered-word',
    },

    onRender: function(){
      if(Accents.TermsApp.refValue){
        this.ui.ref.val( Accents.TermsApp.refValue );
      }
    },

    addTerm: function () {
       console.log('Adding new term: ', this.ui.term.val(), this.ui.ref.val());
       var self = this;
       if( this.currentAlertView ){
         this.currentAlertView.remove();
       }
       var validateTerm = new Accents.Entities.Term({
            term: this.ui.term.val(),
            ref: this.ui.ref.val(),
            user : Accents.user.get('user'),
       });
        var errors = validateTerm.validate();
        if( _.isEmpty(errors) ){
          var termValues = validateTerm.get("term").split(" ");
          _.each(termValues, function(termV){
              var savedModel = new Accents.Entities.Term({
                  id: Accents.Utils.genUUID('xxxxxxxxxx'),
                  term: termV,
                  ref: self.ui.ref.val(),
                  user : Accents.user.get('user'),
                  type: 'term'
              });
              self.collection.add(savedModel);
              savedModel.save({}, {
                  error: function(model, response) {
                      console.log(response.responseText);
                  }
              });
          });
          this.ui.term.val('');
          this.ui.ref.val('');
          this.ui.rendered_word.empty();
          this.ui.term.focus();
        }else{
          this.showErrors(errors);
	}
    },
    updateTerm: function (e) {
      if(e.keyCode == 13){
        this.addTerm();
      }else{
        var pos = this.ui.term[0].selectionStart;
        var term = this.ui.term.val();
        var part = Accents.Utils.renderGlyph2UTF(term.slice(0, pos));
        this.ui.term.val(part + term.slice(pos));
        this.ui.term[0].selectionStart = part.length;
        this.ui.term[0].selectionEnd = part.length;
        // temporarily display HTML version below since we cannot display underscores in input
        this.ui.rendered_word.html(Accents.Utils.renderTypedTerm(this.ui.term.val()));

        Accents.trigger("filter:terms", term);
      }
    },

    showErrors: function(errors){
      var _errors =[];
      if(errors.term){
        _errors.push("Term: " + errors.term);
      }
      if(errors.ref){
        _errors.push("Ref: " + errors.ref);
      }
      this.currentAlertView = new Views.AlertView( {model: new Backbone.Model({errors: _errors}) } );
      //this.$(".form-inline").prepend("
"+ _errors  +"
");
      this.$(".alert-container").html(this.currentAlertView.render().el);
      if( errors.term ){  this.ui.term.parent().addClass("has-error"); }
      if( errors.term ){  this.ui.ref.parent().addClass("has-error"); }
    }
  });

  // temporary add/remove links
  Views.TempLinksView = Backbone.Marionette.ItemView.extend({
    template: '#temp-links-template',
    events: {
         'click button#deleteall': 'deleteAll',
         'click button#generatefakes': 'generateFakes',
    },
    deleteAll: function() {
        while (model = this.collection.first()) {
            model.destroy();
        }
    },
    generateFakes: function () {
        Accents.Entities.fakeTerms(this.collection);
    },
  });

  // table of terms at bottom
  Views.TermView = Backbone.Marionette.ItemView.extend({
    template: '#term-list-item-template',
    tagName: 'tr',
    /*templateHelpers: {
        ilm2html: function() {
            return Accents.Utils.ilm2HTML(this.term);
        }
    }*/
  });

  Views.FilteredTermView = Backbone.Marionette.ItemView.extend({
    template: '#term-filtered-list-item-template',
    tagName: 'tr'
  });

  Views.TermsView = Backbone.Marionette.CompositeView.extend({
    template: '#terms-list-table-template',
    itemView: Views.TermView,
    itemViewContainer: 'tbody',
    collectionEvents: {
        "change reset add remove": "render"
    }
  });

  Views.FilteredTermsView = Backbone.Marionette.CompositeView.extend({
    template: '#terms-filtered-list-table-template',
    itemView: Views.FilteredTermView,
    itemViewContainer: 'tbody',
    collectionEvents: {
        "reset add remove": "render"
    },

    initialize: function(){
      var groupedObject = this.collection.countBy("term");
      var array = [];
      for(object in groupedObject ){
        array.push({term: object, count: groupedObject[object]});
      }
      this.collection = new Backbone.Collection(array);
      Accents.on("filter:terms", this.filterTerms);
    },

    filterTerms: function(term){
      var text = term || ""
      var patt = new RegExp(text, 'i');
      $("#terms-filtered-table table tbody tr").each(function(){
        if( patt.test( $(this).find('td.term').text() )){
          $(this).css("display", "");
        }else{
          $(this).css( "display", "none" );
          return true;
        }
      });
      console.log("Lets filter terms: " + term );
    }

  });

  // table of terms at bottom
  Views.TotalTermsView = Backbone.Marionette.ItemView.extend({
    template: '#term-list-total-template',
    serializeData: function() {
        return {
            "total_count": this.collection.length
        };
    },
    collectionEvents: {
        "change reset add remove": "render",
    },
    tagName: 'h3'
  });

  // add terms main area
  Views.AddTermMainLayout = Marionette.Layout.extend({
    template: '#add-term-main-layout-template',
    regions: {
      add_term_form : "#add-term-form",
      add_remove_links  : "#add-remove-links",
      add_terms_list  : "#add-terms-list",
    }
  });

  // table layout with total at the top
  Views.TermsListLayout = Marionette.Layout.extend({
    template: '#terms-list-layout-template',
    regions: {
      add_term_list_total: "#terms-total",
      add_term_list_table: "#terms-table",
      add_term_filtered_table: "#terms-filtered-table"
    }
  });

  Views.AlertView =  Backbone.Marionette.ItemView.extend({
    template: "#alert-template",

    events:{
      "click .close": "close"
    },

    close: function(e){
      this.remove();
    }
  });

});
<|endoftext|>


<commit_before>"use strict";

module.exports = function (grunt) {
    [
        "node",
        "phantom",
        "rhino",
        "wscript"
    ].forEach(function (runtime) {
        var taskName = "exec:test" + runtime.charAt(0).toUpperCase() + runtime.substr(1) + "Verbose";
        grunt.registerTask(runtime, function (source) {
            var parameter;
            if (undefined === source) {
                parameter = "";
            } else {
                parameter = ":" + source;
            }
            grunt.task.run(taskName + parameter);
        });
    });
};
<commit_msg>Support multiple parameters<commit_after>"use strict";

module.exports = function (grunt) {
    [
        "node",
        "phantom",
        "rhino",
        "wscript"
    ].forEach(function (runtime) {
        var taskName = "exec:test" + runtime.charAt(0).toUpperCase() + runtime.substr(1) + "Verbose";
        grunt.registerTask(runtime, function () {
            var parameter;
            if (0 === arguments.length) {
                parameter = "";
            } else {
                parameter = ":" + [].slice.call(arguments, 0).join(":");
            }
            grunt.task.run(taskName + parameter);
        });
    });
};
<|endoftext|>


<commit_before>import { load as configLoader } from '../config';

const config = configLoader();

export const originMiddleware = async (ctx, next) => {
  ctx.response.set('Access-Control-Allow-Origin', config.origin);
  ctx.response.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  ctx.response.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, X-Authentication-Token, Access-Control-Request-Method');

  await next();
};
<commit_msg>Make the Date response header available via CORS<commit_after>import { load as configLoader } from '../config';

const config = configLoader();

export const originMiddleware = async (ctx, next) => {
  ctx.response.set('Access-Control-Allow-Origin', config.origin);
  ctx.response.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  ctx.response.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, X-Authentication-Token, Access-Control-Request-Method');
  ctx.response.set('Access-Control-Expose-Headers', 'Date');

  await next();
};
<|endoftext|>


<commit_before>module.exports = {
  'env': {
    'es6': false
  },
  'ecmaFeatures': {
    'arrowFunctions': true,
    'blockBindings': true,
    'classes': true,
    'defaultParams': true,
    'destructuring': true,
    'forOf': true,
    'generators': false,
    'modules': true,
    'objectLiteralComputedProperties': true,
    'objectLiteralDuplicateProperties': false,
    'objectLiteralShorthandMethods': true,
    'objectLiteralShorthandProperties': true,
    'spread': true,
    'superInFunctions': true,
    'templateStrings': true,
    'jsx': true
  },
  'rules': {
    // require parens in arrow function arguments
    'arrow-parens': 0,
    // require space before/after arrow function's arrow
    'arrow-spacing': 0,
    // verify super() callings in constructors
    'constructor-super': 0,
    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,
    // disallow modifying variables of class declarations
    'no-class-assign': 0,
    // disallow modifying variables that are declared using const
    'no-const-assign': 2,
    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,
    // require let or const instead of var
    'no-var': 2,
    // require method and property shorthand syntax for object literals
    'object-shorthand': 0,
    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': 2,
    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,
    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,
    // disallow generator functions that do not have yield
    'require-yield': 0
  }
};
<commit_msg>Enable rest params!<commit_after>module.exports = {
  'env': {
    'es6': false
  },
  'ecmaFeatures': {
    'arrowFunctions': true,
    'blockBindings': true,
    'classes': true,
    'defaultParams': true,
    'destructuring': true,
    'forOf': true,
    'generators': false,
    'modules': true,
    'objectLiteralComputedProperties': true,
    'objectLiteralDuplicateProperties': false,
    'objectLiteralShorthandMethods': true,
    'objectLiteralShorthandProperties': true,
    'restParams': true,
    'spread': true,
    'superInFunctions': true,
    'templateStrings': true,
    'jsx': true
  },
  'rules': {
    // require parens in arrow function arguments
    'arrow-parens': 0,
    // require space before/after arrow function's arrow
    'arrow-spacing': 0,
    // verify super() callings in constructors
    'constructor-super': 0,
    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,
    // disallow modifying variables of class declarations
    'no-class-assign': 0,
    // disallow modifying variables that are declared using const
    'no-const-assign': 2,
    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,
    // require let or const instead of var
    'no-var': 2,
    // require method and property shorthand syntax for object literals
    'object-shorthand': 0,
    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': 2,
    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,
    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,
    // disallow generator functions that do not have yield
    'require-yield': 0
  }
};
<|endoftext|>


<commit_before>/**
 * Provides helper functions to traverse the DOM.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @module	WoltLab/WCF/DOM/Traverse
 */
define(['DOM/Util'], function(DOMUtil) {
	"use strict";

	/** @const */ var NONE = 0;
	/** @const */ var SELECTOR = 1;
	/** @const */ var CLASS_NAME = 2;
	/** @const */ var TAG_NAME = 3;

	var _probe = [
		function(el, none) { return true; },
		function(el, selector) { return DOMUtil.matches(el, selector); },
		function(el, className) { return el.classList.contains(className); },
		function(el, tagName) { return el.nodeName === tagName; }
	];

	var _children = function(el, type, value) {
		var children = [];

		for (var i = 0; i < el.childElementCount; i++) {
			if (_probe[type](el.children[i], value)) {
				children.push(el.children[i]);
			}
		}

		return children;
	};

	var _parent = function(el, type, value) {
		el = el.parentNode;

		while (el instanceof Element) {
			if (_probe[type](el, value)) {
				return el;
			}

			el = el.parentNode;
		}

		return null;
	};

	var _sibling = function(el, siblingType, type, value) {
		if (el instanceof Element) {
			if (el[siblingType] !== null && _probe[type](el[siblingType], value)) {
				return el[siblingType];
			}
		}

		return null;
	};

	/**
	 * @constructor
	 */
	function DOMTraverse() {};
	DOMTraverse.prototype = {
		/**
		 * Examines child elements and returns all children matching the given selector.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		selector	CSS selector to match child elements against
		 * @return	{array<Element>}	list of children matching the selector
		 */
		childrenBySel: function(el, selector) {
			return _children(el, SELECTOR, selector);
		},

		/**
		 * Examines child elements and returns all children that have the given CSS class set.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		className	CSS class name
		 * @return	{array<Element>}	list of children with the given class
		 */
		childrenByClass: function(el, className) {
			return _children(el, CLASS_NAME, className);
		},

		/**
		 * Examines child elements and returns all children which equal the given tag.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		tagName		element tag name
		 * @return	{array<Element>}	list of children equaling the tag name
		 */
		childrenByTag: function(el, tagName) {
			return _children(el, TAG_NAME, tagName);
		},

		/**
		 * Examines parent nodes and returns the first parent that matches the given selector.
		 *
		 * @param	{Element}	el		child element
		 * @param	{string}	selector	CSS selector to match parent nodes against
		 * @return	{(Element|null)}	null if no parent node matched the selector
		 */
		parentBySel: function(el, selector) {
			return _parent(el, SELECTOR, selector);
		},

		/**
		 * Examines parent nodes and returns the first parent that has the given CSS class set.
		 *
		 * @param	{Element}	el		child element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no parent node with given class
		 */
		parentByClass: function(el, className) {
			return _parent(el, CLASS_NAME, className);
		},

		/**
		 * Examines parent nodes and returns the first parent which equals the given tag.
		 *
		 * @param	{Element}	el		child element
		 * @param	{string}	tagName		element tag name
		 * @return	{(Element|null)}	null if there is no parent node of given tag type
		 */
		parentByTag: function(el, tagName) {
			return _parent(el, TAG_NAME, tagName);
		},

		/**
		 * Returns the next element sibling.
		 *
		 * @param	{Element}	el		element
		 * @return	{(Element|null)}	null if there is no next sibling element
		 */
		next: function(el) {
			return _sibling(el, 'nextElementSibling', NONE, null);
		},

		/**
		 * Returns the next element sibling that matches the given selector.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	selector	CSS selector to match parent nodes against
		 * @return	{(Element|null)}	null if there is no next sibling element or it does not match the selector
		 */
		nextBySel: function(el, selector) {
			return _sibling(el, 'nextElementSibling', SELECTOR, selector);
		},

		/**
		 * Returns the next element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no next sibling element or it does not have the class set
		 */
		nextByClass: function(el, className) {
			return _sibling(el, 'nextElementSibling', CLASS_NAME, className);
		},

		/**
		 * Returns the next element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no next sibling element or it does not have the class set
		 */
		nextByTag: function(el, tagName) {
			return _sibling(el, 'nextElementSibling', CLASS_NAME, className);
		},

		/**
		 * Returns the previous element sibling.
		 *
		 * @param	{Element}	el		element
		 * @return	{(Element|null)}	null if there is no previous sibling element
		 */
		prev: function(el) {
			return _sibling(el, 'previousElementSibling', NONE, null);
		},

		/**
		 * Returns the previous element sibling that matches the given selector.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	selector	CSS selector to match parent nodes against
		 * @return	{(Element|null)}	null if there is no previous sibling element or it does not match the selector
		 */
		prevBySel: function(el, selector) {
			return _sibling(el, 'previousElementSibling', SELECTOR, selector);
		},

		/**
		 * Returns the previous element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no previous sibling element or it does not have the class set
		 */
		prevByClass: function(el, className) {
			return _sibling(el, 'previousElementSibling', CLASS_NAME, className);
		},

		/**
		 * Returns the previous element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no previous sibling element or it does not have the class set
		 */
		prevByTag: function(el, tagName) {
			return _sibling(el, 'previousElementSibling', CLASS_NAME, className);
		}
	};

	return new DOMTraverse();
});
<commit_msg>Added `childBy*` methods to `DOM/Traverse`<commit_after>/**
 * Provides helper functions to traverse the DOM.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @module	WoltLab/WCF/DOM/Traverse
 */
define(['DOM/Util'], function(DOMUtil) {
	"use strict";

	/** @const */ var NONE = 0;
	/** @const */ var SELECTOR = 1;
	/** @const */ var CLASS_NAME = 2;
	/** @const */ var TAG_NAME = 3;

	var _probe = [
		function(el, none) { return true; },
		function(el, selector) { return DOMUtil.matches(el, selector); },
		function(el, className) { return el.classList.contains(className); },
		function(el, tagName) { return el.nodeName === tagName; }
	];

	var _children = function(el, type, value) {
		var children = [];

		for (var i = 0; i < el.childElementCount; i++) {
			if (_probe[type](el.children[i], value)) {
				children.push(el.children[i]);
			}
		}

		return children;
	};

	var _parent = function(el, type, value) {
		el = el.parentNode;

		while (el instanceof Element) {
			if (_probe[type](el, value)) {
				return el;
			}

			el = el.parentNode;
		}

		return null;
	};

	var _sibling = function(el, siblingType, type, value) {
		if (el instanceof Element) {
			if (el[siblingType] !== null && _probe[type](el[siblingType], value)) {
				return el[siblingType];
			}
		}

		return null;
	};

	/**
	 * @constructor
	 */
	function DOMTraverse() {};
	DOMTraverse.prototype = {
		/**
		 * Examines child elements and returns the first child matching the given selector.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		selector	CSS selector to match child elements against
		 * @return	{(Element|null)}	null if there is no child node matching the selector
		 */
		childBySel: function(el, selector) {
			return _children(el, SELECTOR, selector)[0] || null;
		},

		/**
		 * Examines child elements and returns the first child that has the given CSS class set.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		className	CSS class name
		 * @return	{(Element|null)}	null if there is no child node with given CSS class
		 */
		childByClass: function(el, className) {
			return _children(el, CLASS_NAME, className)[0] || null;
		},

		/**
		 * Examines child elements and returns the first child which equals the given tag.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		tagName		element tag name
		 * @return	{(Element|null)}	null if there is no child node which equals given tag
		 */
		childByTag: function(el, tagName) {
			return _children(el, TAG_NAME, tagName)[0] || null;
		},

		/**
		 * Examines child elements and returns all children matching the given selector.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		selector	CSS selector to match child elements against
		 * @return	{array<Element>}	list of children matching the selector
		 */
		childrenBySel: function(el, selector) {
			return _children(el, SELECTOR, selector);
		},

		/**
		 * Examines child elements and returns all children that have the given CSS class set.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		className	CSS class name
		 * @return	{array<Element>}	list of children with the given class
		 */
		childrenByClass: function(el, className) {
			return _children(el, CLASS_NAME, className);
		},

		/**
		 * Examines child elements and returns all children which equal the given tag.
		 *
		 * @param	{Element}		el		element
		 * @param	{string}		tagName		element tag name
		 * @return	{array<Element>}	list of children equaling the tag name
		 */
		childrenByTag: function(el, tagName) {
			return _children(el, TAG_NAME, tagName);
		},

		/**
		 * Examines parent nodes and returns the first parent that matches the given selector.
		 *
		 * @param	{Element}	el		child element
		 * @param	{string}	selector	CSS selector to match parent nodes against
		 * @return	{(Element|null)}	null if no parent node matched the selector
		 */
		parentBySel: function(el, selector) {
			return _parent(el, SELECTOR, selector);
		},

		/**
		 * Examines parent nodes and returns the first parent that has the given CSS class set.
		 *
		 * @param	{Element}	el		child element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no parent node with given class
		 */
		parentByClass: function(el, className) {
			return _parent(el, CLASS_NAME, className);
		},

		/**
		 * Examines parent nodes and returns the first parent which equals the given tag.
		 *
		 * @param	{Element}	el		child element
		 * @param	{string}	tagName		element tag name
		 * @return	{(Element|null)}	null if there is no parent node of given tag type
		 */
		parentByTag: function(el, tagName) {
			return _parent(el, TAG_NAME, tagName);
		},

		/**
		 * Returns the next element sibling.
		 *
		 * @param	{Element}	el		element
		 * @return	{(Element|null)}	null if there is no next sibling element
		 */
		next: function(el) {
			return _sibling(el, 'nextElementSibling', NONE, null);
		},

		/**
		 * Returns the next element sibling that matches the given selector.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	selector	CSS selector to match parent nodes against
		 * @return	{(Element|null)}	null if there is no next sibling element or it does not match the selector
		 */
		nextBySel: function(el, selector) {
			return _sibling(el, 'nextElementSibling', SELECTOR, selector);
		},

		/**
		 * Returns the next element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no next sibling element or it does not have the class set
		 */
		nextByClass: function(el, className) {
			return _sibling(el, 'nextElementSibling', CLASS_NAME, className);
		},

		/**
		 * Returns the next element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no next sibling element or it does not have the class set
		 */
		nextByTag: function(el, tagName) {
			return _sibling(el, 'nextElementSibling', CLASS_NAME, className);
		},

		/**
		 * Returns the previous element sibling.
		 *
		 * @param	{Element}	el		element
		 * @return	{(Element|null)}	null if there is no previous sibling element
		 */
		prev: function(el) {
			return _sibling(el, 'previousElementSibling', NONE, null);
		},

		/**
		 * Returns the previous element sibling that matches the given selector.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	selector	CSS selector to match parent nodes against
		 * @return	{(Element|null)}	null if there is no previous sibling element or it does not match the selector
		 */
		prevBySel: function(el, selector) {
			return _sibling(el, 'previousElementSibling', SELECTOR, selector);
		},

		/**
		 * Returns the previous element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no previous sibling element or it does not have the class set
		 */
		prevByClass: function(el, className) {
			return _sibling(el, 'previousElementSibling', CLASS_NAME, className);
		},

		/**
		 * Returns the previous element sibling with given CSS class.
		 *
		 * @param	{Element}	el		element
		 * @param	{string}	className	CSS class name
		 * @return	{(Element|null)}	null if there is no previous sibling element or it does not have the class set
		 */
		prevByTag: function(el, tagName) {
			return _sibling(el, 'previousElementSibling', CLASS_NAME, className);
		}
	};

	return new DOMTraverse();
});
<|endoftext|>


<commit_before>// import external dependencies
import 'jquery';

// Import npm dependencies
import 'svgxuse';
import 'foundation-sites/js/foundation.core';
import 'foundation-sites/js/foundation.util.mediaQuery';
import 'foundation-sites/js/foundation.util.keyboard';
import 'foundation-sites/js/foundation.util.box';
import 'foundation-sites/js/foundation.util.nest';
import 'foundation-sites/js/foundation.util.triggers';
import 'foundation-sites/js/foundation.util.motion';
import 'foundation-sites/js/foundation.util.timerAndImageLoader';
import 'foundation-sites/js/foundation.responsiveToggle';
import 'foundation-sites/js/foundation.dropdown';
import 'foundation-sites/js/foundation.reveal';
import 'foundation-sites/js/foundation.sticky';
import 'foundation-sites/js/foundation.accordionMenu';
import 'foundation-sites/js/foundation.magellan';
import 'foundation-sites/js/foundation.tooltip';

// import local dependencies
import Router from './util/router';
import common from './routes/Common';
import home from './routes/Home';
import aboutUs from './routes/About';
import contact from './routes/Contact';
import price from './routes/Princing';

const contactUs = contact;
const tarifs = price;

// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
const routes = {
  // All pages
  common,
  // Home page
  home,
  // About us page, note the change from about-us to aboutUs.
  aboutUs,
  contact,
  contactUs,
  tarifs,
  price,
};

// Load Events
document.addEventListener('DOMContentLoaded', () => new Router(routes).loadEvents());
<commit_msg>correction import pour build<commit_after>// import external dependencies
import 'jquery';

// Import npm dependencies
import 'svgxuse';
import 'foundation-sites/js/foundation.core';
import 'foundation-sites/js/foundation.util.mediaQuery';
import 'foundation-sites/js/foundation.util.keyboard';
import 'foundation-sites/js/foundation.util.box';
import 'foundation-sites/js/foundation.util.nest';
import 'foundation-sites/js/foundation.util.triggers';
import 'foundation-sites/js/foundation.util.motion';
import 'foundation-sites/js/foundation.responsiveToggle';
import 'foundation-sites/js/foundation.dropdown';
import 'foundation-sites/js/foundation.reveal';
import 'foundation-sites/js/foundation.sticky';
import 'foundation-sites/js/foundation.accordionMenu';
import 'foundation-sites/js/foundation.magellan';
import 'foundation-sites/js/foundation.tooltip';

// import local dependencies
import Router from './util/router';
import common from './routes/Common';
import home from './routes/Home';
import aboutUs from './routes/About';
import contact from './routes/Contact';
import price from './routes/Princing';

const contactUs = contact;
const tarifs = price;

// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
const routes = {
  // All pages
  common,
  // Home page
  home,
  // About us page, note the change from about-us to aboutUs.
  aboutUs,
  contact,
  contactUs,
  tarifs,
  price,
};

// Load Events
document.addEventListener('DOMContentLoaded', () => new Router(routes).loadEvents());
<|endoftext|>


<commit_before>module.exports = {
  siteMetadata: {
    title: 'Spree Commerce Documentation',
    titleTemplate: '%s :: Spree Commerce - Ruby on Rails e-commerce platform',
    twitter: '@spreecommerce',
    image: '/images/logo.png',
    siteUrl: 'https://guides.spreecommerce.org',
    description: 'Spree Guides'
  },
  plugins: [
    'gatsby-plugin-sitemap',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-react-helmet-canonical-urls',
      options: {
        siteUrl: 'https://guides.spreecommerce.org',
        noQueryString: true
      },
    },
    'gatsby-transformer-remark',
    'gatsby-plugin-robots-txt',
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          'UA-104990445-1' // Google Analytics / GA
        ],
        // This object is used for configuration specific to this plugin
        pluginConfig: {
          // Puts tracking script in the head instead of the body
          head: true
        }
      }
    },
    {
      resolve: `gatsby-plugin-emotion`,
      options: {
        // Accepts all options defined by `babel-plugin-emotion` plugin.
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `guides`,
        path: `${__dirname}/src/content`
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-component'
            // options: { components: ['json', 'p', 'h1', 'h2', 'h3'] }
          },
          {
            resolve: `gatsby-remark-images`,
            options: {
              quality: 100,
              maxWidth: 1200
            }
          },
          {
            resolve: 'gatsby-remark-external-links',
            options: {
              target: '_blank',
              rel: 'noopener noreferrer'
            }
          },
          // {
          //   resolve: `gatsby-remark-codemirror`,
          //   options: {
          //     // CSS class suffix to be used for produced `<pre/>` blocks.
          //     // Default value is "default", which adds "cm-s-default" class.
          //     // This class name matches
          //     theme: 'smoothy'
          //   }
          // },
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              // Class prefix for
 tags containing syntax highlighting;
              // defaults to 'language-' (eg
).
              // If your site loads Prism into the browser at runtime,
              // (eg for use with libraries like react-live),
              // you may use this to prevent Prism from re-processing syntax.
              // This is an uncommon use-case though;
              // If you're unsure, it's best to use the default value.
              classPrefix: 'language-',
              // This is used to allow setting a language for inline code
              // (i.e. single backticks) by creating a separator.
              // This separator is a string and will do no white-space
              // stripping.
              // A suggested value for English speakers is the non-ascii
              // character '›'.
              inlineCodeMarker: '›',
              // This lets you set up language aliases.  For example,
              // setting this to '{ sh: "bash" }' will let you use
              // the language "sh" which will highlight using the
              // bash highlighter.
              aliases: {},
              // This toggles the display of line numbers alongside the code.
              // To use it, add the following line in src/layouts/index.js
              // right after importing the prism color scheme:
              //  `require("prismjs/plugins/line-numbers/prism-line-numbers.css");`
              // Defaults to false.
              showLineNumbers: false,
              // If setting this to true, the parser won't handle and highlight inline
              // code used in markdown i.e. single backtick code like `this`.
              noInlineHighlight: false
            }
          },
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants'
        ]
      }
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: 'spree-guides',
        short_name: 'guides',
        start_url: '/',
        background_color: '#663399',
        theme_color: '#663399'
      }
    }
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.app/offline
    // 'gatsby-plugin-offline',
  ]
}
<commit_msg>Resize Images so they take less space<commit_after>module.exports = {
  siteMetadata: {
    title: 'Spree Commerce Documentation',
    titleTemplate: '%s :: Spree Commerce - Ruby on Rails e-commerce platform',
    twitter: '@spreecommerce',
    image: '/images/logo.png',
    siteUrl: 'https://guides.spreecommerce.org',
    description: 'Spree Guides'
  },
  plugins: [
    'gatsby-plugin-sitemap',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-react-helmet-canonical-urls',
      options: {
        siteUrl: 'https://guides.spreecommerce.org',
        noQueryString: true
      },
    },
    'gatsby-transformer-remark',
    'gatsby-plugin-robots-txt',
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          'UA-104990445-1' // Google Analytics / GA
        ],
        // This object is used for configuration specific to this plugin
        pluginConfig: {
          // Puts tracking script in the head instead of the body
          head: true
        }
      }
    },
    {
      resolve: `gatsby-plugin-emotion`,
      options: {
        // Accepts all options defined by `babel-plugin-emotion` plugin.
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `guides`,
        path: `${__dirname}/src/content`
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-component'
            // options: { components: ['json', 'p', 'h1', 'h2', 'h3'] }
          },
          {
            resolve: `gatsby-remark-images`,
            options: {
              quality: 100,
              maxWidth: 600,
              withWebp: true
            }
          },
          {
            resolve: 'gatsby-remark-external-links',
            options: {
              target: '_blank',
              rel: 'noopener noreferrer'
            }
          },
          // {
          //   resolve: `gatsby-remark-codemirror`,
          //   options: {
          //     // CSS class suffix to be used for produced `<pre/>` blocks.
          //     // Default value is "default", which adds "cm-s-default" class.
          //     // This class name matches
          //     theme: 'smoothy'
          //   }
          // },
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              // Class prefix for
 tags containing syntax highlighting;
              // defaults to 'language-' (eg
).
              // If your site loads Prism into the browser at runtime,
              // (eg for use with libraries like react-live),
              // you may use this to prevent Prism from re-processing syntax.
              // This is an uncommon use-case though;
              // If you're unsure, it's best to use the default value.
              classPrefix: 'language-',
              // This is used to allow setting a language for inline code
              // (i.e. single backticks) by creating a separator.
              // This separator is a string and will do no white-space
              // stripping.
              // A suggested value for English speakers is the non-ascii
              // character '›'.
              inlineCodeMarker: '›',
              // This lets you set up language aliases.  For example,
              // setting this to '{ sh: "bash" }' will let you use
              // the language "sh" which will highlight using the
              // bash highlighter.
              aliases: { irb: 'ruby' },
              // This toggles the display of line numbers alongside the code.
              // To use it, add the following line in src/layouts/index.js
              // right after importing the prism color scheme:
              //  `require("prismjs/plugins/line-numbers/prism-line-numbers.css");`
              // Defaults to false.
              showLineNumbers: false,
              // If setting this to true, the parser won't handle and highlight inline
              // code used in markdown i.e. single backtick code like `this`.
              noInlineHighlight: false
            }
          },
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants'
        ]
      }
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: 'spree-guides',
        short_name: 'guides',
        start_url: '/',
        background_color: '#663399',
        theme_color: '#663399'
      }
    }
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.app/offline
    // 'gatsby-plugin-offline',
  ]
}
<|endoftext|>


<commit_before>const rollup = require('rollup'),
  json = require('rollup-plugin-json'),
  uglify = require('rollup-plugin-uglify'),
  nodeResolve = require('rollup-plugin-node-resolve'),
  includePaths = require('rollup-plugin-includepaths'),
  commonjs = require('rollup-plugin-commonjs'),
  path = require('path'),
  _ = require('lodash');

const rollupConfig = require('../config/rollup/prod');
const rollupDevConfig = require('../config/rollup/dev');

const webpack = require('webpack-stream');
const webpackConfig = require('../config/webpack/webpack.config.js');

function _createWebpackBundle(gulp, config) {
  const entryFile = config.mainJS.indexFile;
  const destFile = path.join(config.mainJS.name + '.umd.min.js');
  const dest = path.join(config.outputFolder, 'js');

  if (!webpackConfig.output) {
    webpackConfig.output = {};
  }

  webpackConfig.output = Object.assign({}, webpackConfig.output, { filename: destFile });

  return gulp.src(entryFile)
    .pipe(webpack(webpackConfig))
    .pipe(gulp.dest(dest));
}

module.exports = function setupTask(gulp, bundles, bundlerOpts) {
  function task() {
    var tps = [];
    for (var idx = 0; idx < bundles.length; idx++) {
      var config = bundles[idx];
      for (var i = 0; i < config.formats.length; i++) {
        var format = config.formats[i],
          moduleName = config.moduleNameJS,
          dest = null,
          src = null;
        if (!path.isAbsolute(config.mainJS.indexFile)) {
          src = path.join(bundlerOpts.workingDir, config.mainJS.indexFile);
        }
        else {
          src = config.mainJS.indexFile;
        }
        if (format === 'es') {
          if (!path.isAbsolute(config.outputFolder)) {
            dest = path.join(bundlerOpts.workingDir, config.outputFolder, 'js', config.name || '', config.mainJS.name + '.es2015.js');
          }
          else {
            dest = path.join(config.outputFolder, 'js', config.name || '', config.mainJS.name + '.es2015.js');
          }
          tps.push(bundleES6(src, dest, config.externalMappings));
        }
        else {
          const useWebpack = true;
          if (useWebpack) {
            const webpackTask = _createWebpackBundle(gulp, config);
            tps.push(webpackTask);
          } else {
            if (!path.isAbsolute(config.outputFolder)) {
              dest = path.join(bundlerOpts.workingDir, config.outputFolder, 'js', config.name || '', config.mainJS.name + '.' + format + '-es2015.js');
            }
            else {
              dest = path.join(config.outputFolder, 'js', config.name || '', config.mainJS.name + '.' + format + '-es2015.js');
            }
            tps.push(transpileWithRollup(src, dest, format, moduleName, config.externalMappings));
          }
        }
      }
    }
    return Promise.all(tps);
  }
  // NOTE: To not execute a task each time the gulpfile defines a task with
  // gulp.task('task-name', ...) we return a function here, which gets called
  // eventually when calling a task via gulp.
  return task;
}

function bundleES6(indexFile, dest, externalMappings) {
  // console.log('[bundleES6] src: %s | dest: %s', indexFile, dest);

  // All external mappings have to be skipped by the nodeResolve plugin. Otherwise
  // the plugin would search for them in node_modules and complain if they are not found.
  var nodeResolveSkips = _.map(externalMappings, function (value, key) {
    return key;
  });

  // console.log('[bundle-js::bundleES6] index file:  ' + indexFile);
  // console.log('[bundle-js::bundleES6] dest folder: ' + dest);

  return rollup.rollup({
    entry: indexFile,
    external: [],
    plugins: [
      json(),
      // includePaths(includePathOptions),
      nodeResolve({
        jsnext: true,
        main: true,
        skip: nodeResolveSkips
      }),
      commonjs(),
      // filesize()
    ]
  }).then(function (bundle) {
    console.log('[bundle-js]: bundling: ', dest);
    return bundle.write({
      format: 'es',
      dest: dest
    });
  });
}

function transpileWithRollup(indexFile, dest, format, moduleName, externalMappings) {
  // console.log('[transpileWithRollup] src: %s | dest: %s', indexFile, dest);

  // All external mappings have to be skipped by the nodeResolve plugin. Otherwise
  // the plugin would search for them in node_modules and complain if they are not found.
  var nodeResolveSkips = _.map(externalMappings, function (value, key) {
    return key;
  });

  // console.log('[bundle-js::transpileWithRollup] index file:  ' + indexFile);
  // console.log('[bundle-js::transpileWithRollup] dest folder: ' + dest);

  var tps = [];

  rollupDevConfig.entry = indexFile;

  console.log('rollupDevConfig: ', rollupDevConfig);

  tps.push(rollup.rollup(rollupDevConfig
  //   {
  //   entry: indexFile,
  //   external: [],
  //   plugins: [
  //     json(),
  //     string({
  //       extensions: ['.tmpl']
  //     }),
  //     // includePaths(includePathOptions),
  //     nodeResolve({
  //       jsnext: true,
  //       main: true,
  //       skip: nodeResolveSkips
  //     }),
  //
  //     // CAUTION: make sure to initialize all file transforming additional plugins
  //     // BEFORE babel() or buble(). Otherwise the transpiler will consume the
  //     //imported files first.
  //     // babel(),
  //     buble(),
  //     commonjs(),
  //     // filesize()
  //   ]
  // }
).then(function (bundle) {
    // console.log('[bundle-js]: transpiling: ', dest);
    return bundle.write({
      format: format,
      moduleName: moduleName,
      globals: externalMappings,
      dest: dest,
      useStrict: false // NOTE: necessary for Safari when using web components. See https://github.com/ibm-js/delite/issues/259
    });
  }));

  console.log('rollupConfig: ', rollupConfig);

  tps.push(rollup.rollup(rollupConfig
  //   entry: indexFile,
  //   external: [],
  //   plugins: [
  //     json(),
  //     string({
  //       extensions: ['.tmpl']
  //     }),
  //     // includePaths(includePathOptions),
  //     nodeResolve({
  //       jsnext: true,
  //       main: true,
  //       skip: nodeResolveSkips
  //     }),
  //     // CAUTION: make sure to initialize all file transforming additional plugins
  //     // BEFORE babel() or buble(). Otherwise the transpiler will consume the
  //     //imported files first.
  //     // babel(),
  //     buble(),
  //     commonjs(),
  //     // filesize(),
  //     uglify()
  //   ]
  // }
  ).then(function (bundle) {
    var dirname = path.dirname(dest),
      basename = path.basename(dest, '.js'),
      destMin = path.join(dirname, basename) + '.min.js';
    console.log('[bundle-js]: minifying: ', destMin);
    return bundle.write({
      format: format,
      moduleName: moduleName,
      globals: externalMappings,
      dest: destMin,
      useStrict: false // NOTE: necessary for Safari when using web components. See https://github.com/ibm-js/delite/issues/259
    });
  }));

  return Promise.all(tps);
}
<commit_msg>disabled creation of concatenated ES2015 dist file<commit_after>const rollup = require('rollup'),
  json = require('rollup-plugin-json'),
  uglify = require('rollup-plugin-uglify'),
  nodeResolve = require('rollup-plugin-node-resolve'),
  includePaths = require('rollup-plugin-includepaths'),
  commonjs = require('rollup-plugin-commonjs'),
  path = require('path'),
  _ = require('lodash');

const rollupConfig = require('../config/rollup/prod');
const rollupDevConfig = require('../config/rollup/dev');

const webpack = require('webpack-stream');
const webpackConfig = require('../config/webpack/webpack.config.js');

function _createWebpackBundle(gulp, config) {
  const entryFile = config.mainJS.indexFile;
  const destFile = path.join(config.mainJS.name + '.umd.min.js');
  const dest = path.join(config.outputFolder, 'js');

  if (!webpackConfig.output) {
    webpackConfig.output = {};
  }

  webpackConfig.output = Object.assign({}, webpackConfig.output, { filename: destFile });

  return gulp.src(entryFile)
    .pipe(webpack(webpackConfig))
    .pipe(gulp.dest(dest));
}

module.exports = function setupTask(gulp, bundles, bundlerOpts) {
  function task() {
    var tps = [];
    for (var idx = 0; idx < bundles.length; idx++) {
      var config = bundles[idx];
      for (var i = 0; i < config.formats.length; i++) {
        var format = config.formats[i],
          moduleName = config.moduleNameJS,
          dest = null,
          src = null;
        if (!path.isAbsolute(config.mainJS.indexFile)) {
          src = path.join(bundlerOpts.workingDir, config.mainJS.indexFile);
        }
        else {
          src = config.mainJS.indexFile;
        }
        if (format === 'es') {
          if (!path.isAbsolute(config.outputFolder)) {
            dest = path.join(bundlerOpts.workingDir, config.outputFolder, 'js', config.name || '', config.mainJS.name + '.es2015.js');
          }
          else {
            dest = path.join(config.outputFolder, 'js', config.name || '', config.mainJS.name + '.es2015.js');
          }
          tps.push(bundleES6(src, dest, config.externalMappings));
        }
        else {
          const useWebpack = true;
          if (useWebpack) {
            const webpackTask = _createWebpackBundle(gulp, config);
            tps.push(webpackTask);
          } else {
            if (!path.isAbsolute(config.outputFolder)) {
              dest = path.join(bundlerOpts.workingDir, config.outputFolder, 'js', config.name || '', config.mainJS.name + '.' + format + '-es2015.js');
            }
            else {
              dest = path.join(config.outputFolder, 'js', config.name || '', config.mainJS.name + '.' + format + '-es2015.js');
            }
            tps.push(transpileWithRollup(src, dest, format, moduleName, config.externalMappings));
          }
        }
      }
    }
    return Promise.all(tps);
  }
  // NOTE: To not execute a task each time the gulpfile defines a task with
  // gulp.task('task-name', ...) we return a function here, which gets called
  // eventually when calling a task via gulp.
  return task;
}

function bundleES6(indexFile, dest, externalMappings) {
  console.log('R> ES2015 bundling is disabled for now. You can import the entry file directly into your projects.');
  return;
  // console.log('[bundleES6] src: %s | dest: %s', indexFile, dest);

  // All external mappings have to be skipped by the nodeResolve plugin. Otherwise
  // the plugin would search for them in node_modules and complain if they are not found.
  var nodeResolveSkips = _.map(externalMappings, function (value, key) {
    return key;
  });

  // console.log('[bundle-js::bundleES6] index file:  ' + indexFile);
  // console.log('[bundle-js::bundleES6] dest folder: ' + dest);

  return rollup.rollup({
    entry: indexFile,
    external: [],
    plugins: [
      json(),
      // includePaths(includePathOptions),
      nodeResolve({
        jsnext: true,
        main: true,
        skip: nodeResolveSkips
      }),
      commonjs(),
      // filesize()
    ]
  }).then(function (bundle) {
    console.log('[bundle-js]: bundling: ', dest);
    return bundle.write({
      format: 'es',
      dest: dest
    });
  });
}

function transpileWithRollup(indexFile, dest, format, moduleName, externalMappings) {
  // console.log('[transpileWithRollup] src: %s | dest: %s', indexFile, dest);

  // All external mappings have to be skipped by the nodeResolve plugin. Otherwise
  // the plugin would search for them in node_modules and complain if they are not found.
  var nodeResolveSkips = _.map(externalMappings, function (value, key) {
    return key;
  });

  // console.log('[bundle-js::transpileWithRollup] index file:  ' + indexFile);
  // console.log('[bundle-js::transpileWithRollup] dest folder: ' + dest);

  var tps = [];

  rollupDevConfig.entry = indexFile;

  console.log('rollupDevConfig: ', rollupDevConfig);

  tps.push(rollup.rollup(rollupDevConfig
  //   {
  //   entry: indexFile,
  //   external: [],
  //   plugins: [
  //     json(),
  //     string({
  //       extensions: ['.tmpl']
  //     }),
  //     // includePaths(includePathOptions),
  //     nodeResolve({
  //       jsnext: true,
  //       main: true,
  //       skip: nodeResolveSkips
  //     }),
  //
  //     // CAUTION: make sure to initialize all file transforming additional plugins
  //     // BEFORE babel() or buble(). Otherwise the transpiler will consume the
  //     //imported files first.
  //     // babel(),
  //     buble(),
  //     commonjs(),
  //     // filesize()
  //   ]
  // }
).then(function (bundle) {
    // console.log('[bundle-js]: transpiling: ', dest);
    return bundle.write({
      format: format,
      moduleName: moduleName,
      globals: externalMappings,
      dest: dest,
      useStrict: false // NOTE: necessary for Safari when using web components. See https://github.com/ibm-js/delite/issues/259
    });
  }));

  console.log('rollupConfig: ', rollupConfig);

  tps.push(rollup.rollup(rollupConfig
  //   entry: indexFile,
  //   external: [],
  //   plugins: [
  //     json(),
  //     string({
  //       extensions: ['.tmpl']
  //     }),
  //     // includePaths(includePathOptions),
  //     nodeResolve({
  //       jsnext: true,
  //       main: true,
  //       skip: nodeResolveSkips
  //     }),
  //     // CAUTION: make sure to initialize all file transforming additional plugins
  //     // BEFORE babel() or buble(). Otherwise the transpiler will consume the
  //     //imported files first.
  //     // babel(),
  //     buble(),
  //     commonjs(),
  //     // filesize(),
  //     uglify()
  //   ]
  // }
  ).then(function (bundle) {
    var dirname = path.dirname(dest),
      basename = path.basename(dest, '.js'),
      destMin = path.join(dirname, basename) + '.min.js';
    console.log('[bundle-js]: minifying: ', destMin);
    return bundle.write({
      format: format,
      moduleName: moduleName,
      globals: externalMappings,
      dest: destMin,
      useStrict: false // NOTE: necessary for Safari when using web components. See https://github.com/ibm-js/delite/issues/259
    });
  }));

  return Promise.all(tps);
}
<|endoftext|>


<commit_before>import React from "react";
import {isNil} from "lodash";
import SelectField from "./SelectField";
import {formatBytes} from "../utils/Format";
import {HubConnectionBuilder} from "@microsoft/signalr";
import {Api} from "../utils/Api";

const initialState = {
    loading: true,
    medias: null
}

export default function MediaSelectField(props) {
    const {
        id,
        label,
        path,
        onChange,
    } = props

    const api = React.useMemo(() => new Api(), []);

    const [state, setState] = React.useState({...initialState})
    const [connection, setConnection] = React.useState(null);

    const {
        loading,
        medias
    } = state

    React.useEffect(() => {
        if (!isNil(connection)) {
            return
        }

        const newConnection = new HubConnectionBuilder()
            .withUrl('/hubs/result')
            .withAutomaticReconnect()
            .build();

        setConnection(newConnection)
    }, [connection, setConnection]);

    React.useEffect(() => {
        if (connection && connection.state !== "Connected") {
            connection.start()
                .then(result => {
                    connection.on('List', mediaInfos => {
                        setState({
                            medias: mediaInfos || []
                        })
                    });
                })
                .catch(e => console.log('Connection failed: ', e));
        }
    }, [connection, setState, state]);

    const handleGetMedias = React.useCallback(() => {
        async function getMedias() {
            await api.list()
            setState({
                ...state,
                loading: false
            })
        }
        getMedias()
    }, [api, setState, state])

    React.useEffect(() => {
        if (!loading) {
            return
        }
        handleGetMedias()
    }, [loading, state.session, handleGetMedias])

    const handleChange = (path) => {
        if (isNil(onChange)) {
            return
        }
        const media = (medias || []).find(media => media.path === path)
        onChange(media)
    }

    return (
        <SelectField
            label={label}
            id={id}
            value={path || ''}
            options={(medias || []).map((media) => {
                return {
                    title: `${media.model} (${formatBytes(media.diskSize)})`,
                    value: media.path
                }
            })}
            onChange={(value) => handleChange(value)}
        />
    )
}<commit_msg>Add none available when no medias are detected<commit_after>import React from "react";
import {isNil} from "lodash";
import SelectField from "./SelectField";
import {formatBytes} from "../utils/Format";
import {HubConnectionBuilder} from "@microsoft/signalr";
import {Api} from "../utils/Api";

const initialState = {
    loading: true,
    medias: null
}

export default function MediaSelectField(props) {
    const {
        id,
        label,
        path,
        onChange,
    } = props

    const api = React.useMemo(() => new Api(), []);

    const [state, setState] = React.useState({...initialState})
    const [connection, setConnection] = React.useState(null);

    const {
        loading,
        medias
    } = state

    React.useEffect(() => {
        if (!isNil(connection)) {
            return
        }

        const newConnection = new HubConnectionBuilder()
            .withUrl('/hubs/result')
            .withAutomaticReconnect()
            .build();

        setConnection(newConnection)
    }, [connection, setConnection]);

    React.useEffect(() => {
        if (connection && connection.state !== "Connected") {
            connection.start()
                .then(result => {
                    connection.on('List', mediaInfos => {
                        setState({
                            medias: mediaInfos || []
                        })
                    });
                })
                .catch(e => console.log('Connection failed: ', e));
        }
    }, [connection, setState, state]);

    const handleGetMedias = React.useCallback(() => {
        async function getMedias() {
            await api.list()
            setState({
                ...state,
                loading: false
            })
        }
        getMedias()
    }, [api, setState, state])

    React.useEffect(() => {
        if (!loading) {
            return
        }
        handleGetMedias()
    }, [loading, state.session, handleGetMedias])

    const handleChange = (path) => {
        if (isNil(onChange)) {
            return
        }
        const media = (medias || []).find(media => media.path === path)
        onChange(media)
    }

    return (
        <SelectField
            label={label}
            id={id}
            emptyLabel="None available"
            value={path || ''}
            options={(medias || []).map((media) => {
                return {
                    title: `${media.model} (${formatBytes(media.diskSize)})`,
                    value: media.path
                }
            })}
            onChange={(value) => handleChange(value)}
        />
    )
}<|endoftext|>


<commit_before>Trisano.CmrsModifiedTabs = {

    initialTabHtml : {},

    initialHasFollowupElements : {},

    init : function() {
        var self = this;

        $j("div.tab").each(function(t) {
            var tab_key = '';
            var tab_id = $j(this).attr('id');

            $j(this).find('*').each(function(c) {
                var value = $j(this).val();
                var name = $j(this).attr('name');
                var id = $j(this).attr('id');
                tab_key += value;

                if (self.hasFollowupElement(name)) {
                    self.initialHasFollowupElements[name] = value;
                }
                else if (name == "morbidity_event[disease_event_attributes][disease_id]") {
                    self.initialHasFollowupElements[name] = value;
                }

                if (id && id.match(/investigat/)) {
                    tab_key = "INVALIDATE"; // always invalidate tab caches that include investigation questions/answers
                }
            });

            $j(this).find(':checked').each(function() {
                tab_key += $j(this).attr('name') + '1';
            });

            self.initialTabHtml[tab_id] = tab_key;
        });

        this.prefetchShow();
    },

    /**
     * Prefetch the show page to ensure it is in the cache
     */
    prefetchShow : function() {
        var url = window.location.pathname;
        url = url.replace(/\/edit/, '');

        $j.ajax({
          url: url,
          complete: function() {
            // Do nothing
          }
        });
    },

    setChangedTabs : function() {
        var self = this;

        $j("div.tab").each(function(t) {
            var id = $j(this).attr('id');
            var initial = self.initialTabHtml[id];
            var current = '';

            $j(this).find('*').each(function(c) {
                var name = $j(this).attr('name');
                var value = $j(this).val();
                current += value;
                if (self.initialHasFollowupElements[name] != undefined && self.initialHasFollowupElements[name] != value) {
                    self.expireAll();
                }
            });

            $j(this).find(':checked').each(function() {
                current += $j(this).attr('name') + '1';
            });

            if (current != initial) {
                var form = $j(".edit_morbidity_event").first();
                $j('<input>').attr({
                    type: 'hidden',
                    name: 'expire_cache[' + id + ']',
                    value: true
                }).appendTo(form);
            }
        });
    },

    hasFollowupElement : function(name) {
        return (Trisano.FollowupCorePaths[name]) ? true : false;
    },

    expireAll : function() {
        var form = $j(".edit_morbidity_event").first();
        $j('<input>').attr({
            type: 'hidden',
            name: 'expire_cache_all',
            value: true
        }).appendTo(form);
    }

};

$j(document).ready(function() {
    Trisano.CmrsModifiedTabs.init();
});<commit_msg>Always invalidate tab caches that include investigation questions/answers<commit_after>Trisano.CmrsModifiedTabs = {

    initialTabHtml : {},

    initialHasFollowupElements : {},

    affectedInvestigationTabs : {},

    init : function() {
        var self = this;

        $j("div.tab").each(function(t) {
            var tab_key = '';
            var tab_id = $j(this).attr('id');

            $j(this).find('*').each(function(c) {
                var value = $j(this).val();
                var name = $j(this).attr('name');
                var id = $j(this).attr('id');
                tab_key += value;

                if (self.hasFollowupElement(name)) {
                    self.initialHasFollowupElements[name] = value;
                }
                else if (name == "morbidity_event[disease_event_attributes][disease_id]") {
                    self.initialHasFollowupElements[name] = value;
                }

                if (id && id.match(/investigat/)) {
                    self.affectedInvestigationTabs[tab_id] = true;
                }
            });

            $j(this).find(':checked').each(function() {
                tab_key += $j(this).attr('name') + '1';
            });

            self.initialTabHtml[tab_id] = tab_key;
        });

        this.prefetchShow();
    },

    /**
     * Prefetch the show page to ensure it is in the cache
     */
    prefetchShow : function() {
        var url = window.location.pathname;
        url = url.replace(/\/edit/, '');

        $j.ajax({
          url: url,
          complete: function() {
            // Do nothing
          }
        });
    },

    setChangedTabs : function() {
        var self = this;

        $j("div.tab").each(function(t) {
            var id = $j(this).attr('id');
            var initial = self.initialTabHtml[id];
            var current = '';

            $j(this).find('*').each(function(c) {
                var name = $j(this).attr('name');
                var value = $j(this).val();
                current += value;
                if (self.initialHasFollowupElements[name] != undefined && self.initialHasFollowupElements[name] != value) {
                    self.expireAll();
                }
            });

            $j(this).find(':checked').each(function() {
                current += $j(this).attr('name') + '1';
            });

            if (current != initial) {
                self.expireTab(id);

                if (self.affectedInvestigationTabs[id]) {
                    self.expireTab('investigation_tab');

                    $j.each(self.affectedInvestigationTabs, function(i, v) {
                        self.expireTab(i);
                    });
                }
            }
        });
    },

    expireTab : function(id) {
        var form = $j(".edit_morbidity_event").first();
        $j('<input>').attr({
            type: 'hidden',
            name: 'expire_cache[' + id + ']',
            value: true
        }).appendTo(form);
    },

    hasFollowupElement : function(name) {
        return (Trisano.FollowupCorePaths[name]) ? true : false;
    },

    expireAll : function() {
        var form = $j(".edit_morbidity_event").first();
        $j('<input>').attr({
            type: 'hidden',
            name: 'expire_cache_all',
            value: true
        }).appendTo(form);
    }

};

$j(document).ready(function() {
    Trisano.CmrsModifiedTabs.init();
});<|endoftext|>


<commit_before>'use strict';

var asts    = require('pegjs/lib/compiler/asts');
var visitor = require('pegjs/lib/compiler/visitor');

function Type(kind, name, value) {
  this.kind  = kind;
  this.name  = name;
  this.value = value;
}
function buildVisitor(functions) {
  function visit(type) {
    if (!type.kind) {
      throw new Error('Invalid `type`: has no property `kind`');
    }
    var f = functions[type.kind];
    if (!f) {
      throw new Error('No visitor function for type `' + type.kind + '`', type);
    }
    return f.apply(null, arguments);
  }
  return visit;
};

var noneType  = new Type('none');
var unitType  = new Type('unit');
var rangeType = new Type('range');

function none(node)  { return node.result.type = noneType; }
function unit(node)  { return node.result.type = unitType; }
function range(node) { return node.result.type = rangeType; }

/// Выводит типы всех узлов грамматики на основе типов action-узлов.
/// Типы action узлов должны быть предварительно размечены, например, проходом init-types.
function inferenceTypes(ast, options) {
  var emitError = options.collector.emitError;

  var i = 0;
  /// Генератор уникальных имен для типов.
  function gen() {
    ++i;
    return 'T' + i;
  }

  // Устанавливает узлу выходной тип, равный типу списка из элементов одного типа - типа его выражения.
  function list(node)     { return node.result.type = new Type('list', gen(), inference(node.expression)); }
  // Устанавливает узлу выходной тип, равный типу его выражения.
  function delegate(node) { return node.result.type = inference(node.expression); }

  // Сначала инициализируем все правила каким-то типом.
  // Каждое правило всегда имеет какой-то тип, по умолчанию - какой-то пользовательский,
  // структуру которого еще предстоит выяснить.
  ast.rules.forEach(rule => rule.result.type = new Type('rule', rule.name));

  // Список узлов, посещенных до входа в узел `rule_ref`. Помогает нахотить рекурсивные типы.
  var visitedNodes = [];
  var inference = visitor.build({
    rule:         function(node) {
      visitedNodes.push(node);
      var type = inference(node.expression);
      visitedNodes.pop();
      // На `node.result.type` ссылается множество `rule_ref` узлов. При этом, точный тип данного
      // узла может стать известным позже, чем данные ссылки будут установлены. Чтобы не заменять
      // типы во всех ссылающихся (прямо и косвенно) на данный узел узлов AST, мы храним тип правила
      // в специальном узле, который просто перенаправляет нас на реальный его тип.
      // Когда реальный тип узла правила становится известным, мы просто заменяем внутренний тип.
      return node.result.type.value = type;
    },
    named:        delegate,
    choice:       function(node) {
      return node.result.type = new Type('enum', gen(), node.alternatives.map(inference));
    },
    action:       function(node) {
      inference(node.expression);
      var type = node.result.type;
      if (type) {
        // Действию извне должны были задать либо конечный тип, либо функцию вывода типа
        // из типа меток, доступных действию.
        if (type instanceof Type) {
          return node.result.type;
        } else
        if (typeof(type) === 'function') {
          // Возвращаемый тип действия может зависеть от типов помеченных выражений.
          // Наиболее частый случай этого - возврат лишь одного элемента из последовательности.
          type = type();
          if (type instanceof Type) {
            return node.result.type = type;
          }
          emitError("Type generator for action must return instance of 'Type', but returned object has type "+typeof(type), node.location);
        } else {
          emitError("Action result type must be 'Type' instance or function, but it type is "+typeof(type), node.location);
        }
      } else {
        emitError('Action result type not defined', node.location);
      }
    },
    sequence:     function(node) {
      return node.result.type = new Type('tuple', gen(), node.elements.map(inference));
    },
    labeled:      delegate,
    text:         range,
    simple_and:   none,
    simple_not:   none,
    optional:     function(node) {
      return node.result.type = new Type('option', gen(), inference(node.expression));
    },
    zero_or_more: list,
    one_or_more:  list,
    range:        list,
    semantic_and: none,
    semantic_not: none,
    rule_ref:     function(node) {
      var rule = asts.findRule(ast, node.name);
      var isRecursive = visitedNodes.indexOf(rule) >= 0;
      // У всех правил есть хоть какой-то тип, возможно, еще не вычисленный. Тем не менее, ссылаться
      // на него можно. В случае рекурсивного типа ссылаемся на него через вспомогательный тип ref.
      return node.result.type = isRecursive ? new Type('ref', gen(), rule.result.type) : rule.result.type;
    },
    literal:      range,
    "class":      unit,
    any:          unit,
  });

  inference(ast);
}

// Данный файл может сразу использоваться, как плагин
module.exports = {
  Type: Type,
  buildVisitor: buildVisitor,

  use: function(config) {
    config.passes.transform.push(inferenceTypes);
  },
  pass: inferenceTypes,
};
<commit_msg>Исправления и комментарии в проходе inference-types<commit_after>'use strict';

let asts    = require('pegjs/lib/compiler/asts');
let visitor = require('pegjs/lib/compiler/visitor');

/// Виды типов:
/// Примитивные:
/// - 'none': тип значений, возвращаемых из семантических предикатов, например, 'bool'.
///   Данный тип должно быть возможно использовать в логических выражениях с двоичной логикой.
/// - 'unit': тип одного элемента входной последовательности, например, 'char'.
///   Данный тип имеют результаты разбора одиночного символа и класса символов.
/// - 'range': тип входной последовательности, например, 'std::string'.
///   Данный тип имеет результат разбора литерала и оператор взятия совпавшей части
///   последовательности ($).
/// Составные:
/// - 'enum': тип, способный хранить в себе один из дочерних типов, например, 'boost::variant'.
///   Является результатом обработки узлов выбора альтернативы.
/// - 'list': тип для представления списка элементов дочернего типа, например, 'std::vector'.
///   Является результатом обработки узлов повторений элементов (*, +, range)
/// - 'tuple': тип, хранящий в себе все дочерные типы в указанном порядке, например, 'std::tuple'.
///   Данный тип генерирует только узел последовательности элементов.
/// - 'option': тип, хранящий в себе дочерний тип или признак того, что разбор оказался неуспешен.
///   Данный тип генерирует только узел опционального элемента.
/// - 'ref': тип, описывающий ссылку на свой дочерный тип, например '&'.
///   Данный тип генерирует только узел ссылки на правило.
/// Фантомные:
/// - 'rule': тип, изначально приписываемый какому-то правилу, для возможности вычисления цикличеких
///   ссылок.
/// - 'error': тип, приписываемый узлам действия в случае, если у них не задан собственный тип.
function Type(kind, name, value) {
  this.kind  = kind;
  this.name  = name;
  this.value = value;
}
function buildVisitor(functions) {
  function visit(type) {
    if (!type.kind) {
      throw new Error('Invalid `type`: has no property `kind`');
    }
    let f = functions[type.kind];
    if (!f) {
      throw new Error('No visitor function for type `' + type.kind + '`', type);
    }
    return f.apply(null, arguments);
  }
  return visit;
};

const noneType  = new Type('none');
const unitType  = new Type('unit');
const rangeType = new Type('range');

function none(node)  { return node.result.type = noneType; }
function unit(node)  { return node.result.type = unitType; }
function range(node) { return node.result.type = rangeType; }

/// Выводит типы всех узлов грамматики на основе типов action-узлов.
/// Типы action узлов должны быть предварительно размечены, например, проходом init-types.
function inferenceTypes(ast, options) {
  let emitError = options.collector.emitError;

  let i = 0;
  /// Генератор уникальных имен для типов.
  function gen() {
    ++i;
    return 'T' + i;
  }

  // Устанавливает узлу выходной тип, равный типу списка из элементов одного типа - типа его выражения.
  function list(node)     { return node.result.type = new Type('list', gen(), inference(node.expression)); }
  // Устанавливает узлу выходной тип, равный типу его выражения.
  function delegate(node) { return node.result.type = inference(node.expression); }

  // Сначала инициализируем все правила каким-то типом.
  // Каждое правило всегда имеет какой-то тип, по умолчанию - какой-то пользовательский,
  // структуру которого еще предстоит выяснить.
  ast.rules.forEach(rule => rule.result.type = new Type('rule', rule.name));

  // Список узлов, посещенных до входа в узел `rule_ref`. Помогает находить рекурсивные типы.
  let visitedNodes = [];
  var inference = visitor.build({
    rule:         function(node) {
      visitedNodes.push(node);
      let type = inference(node.expression);
      visitedNodes.pop();
      // На `node.result.type` ссылается множество `rule_ref` узлов. При этом, точный тип данного
      // узла может стать известным позже, чем данные ссылки будут установлены. Чтобы не заменять
      // типы во всех ссылающихся (прямо и косвенно) на данный узел узлов AST, мы храним тип правила
      // в специальном узле, который просто перенаправляет нас на реальный его тип.
      // Когда реальный тип узла правила становится известным, мы просто заменяем внутренний тип.
      return node.result.type.value = type;
    },
    named:        delegate,
    choice:       function(node) {
      return node.result.type = new Type('enum', gen(), node.alternatives.map(inference));
    },
    action:       function(node) {
      inference(node.expression);
      let type = node.result.type;
      if (!type) {
        emitError('Action result type not defined', node.location);
        return node.result.type = new Type('error', gen());
      }
      // Действию извне должны были задать либо конечный тип, либо функцию вывода типа
      // из типа меток, доступных действию.
      if (type instanceof Type) {
        return type;
      }
      if (typeof(type) !== 'function') {
        emitError("Action result type must be 'Type' instance or function, but it type is "+typeof(type), node.location);
        return node.result.type = new Type('error', gen());
      }
      // Возвращаемый тип действия может зависеть от типов помеченных выражений.
      // Наиболее частый случай этого - возврат лишь одного элемента из последовательности.
      type = type();
      if (type instanceof Type) {
        return node.result.type = type;
      }
      emitError("Type generator for action must return instance of 'Type', but returned object has type "+typeof(type), node.location);
      return node.result.type = new Type('error', gen());
    },
    sequence:     function(node) {
      return node.result.type = new Type('tuple', gen(), node.elements.map(inference));
    },
    labeled:      delegate,
    text:         range,
    simple_and:   none,
    simple_not:   none,
    optional:     function(node) {
      return node.result.type = new Type('option', gen(), inference(node.expression));
    },
    zero_or_more: list,
    one_or_more:  list,
    range:        function(node) {
      if (node.delimiter) {
        inference(node.delimiter);
      }
      return list(node);
    },
    group:        delegate,
    semantic_and: none,
    semantic_not: none,
    rule_ref:     function(node) {
      var rule = asts.findRule(ast, node.name);
      var isRecursive = visitedNodes.indexOf(rule) >= 0;
      // У всех правил есть хоть какой-то тип, возможно, еще не вычисленный. Тем не менее, ссылаться
      // на него можно. В случае рекурсивного типа ссылаемся на него через вспомогательный тип ref.
      return node.result.type = isRecursive ? new Type('ref', gen(), rule.result.type) : rule.result.type;
    },
    literal:      range,
    'class':      unit,
    any:          unit,
  });

  inference(ast);
}

// Данный файл может сразу использоваться, как плагин
module.exports = {
  Type: Type,
  buildVisitor: buildVisitor,

  use: function(config) {
    config.passes.transform.push(inferenceTypes);
  },
  pass: inferenceTypes,
};
<|endoftext|>


<commit_before>define(function(require) {
	"use strict";

	var Backbone = require('backbone');
	var _ = require('underscore');
	var ConversationModel = require("models/conversation");
	var ConversationEvents = require('events/conversation-event');
	require('bootpag');
	require('moment');

	var HistoryListItemView = Backbone.View.extend({
		tagName : 'li',
		events : {
			"click a" : "renderConversationEvent"
		},
		template : _.template($('#tpl-history-list-item').html()),

		renderConversationEvent : function(event){
			var conversation = new ConversationModel({
				id : $(event.currentTarget).data('historyId')
			});
			conversation.fetch({
				success : function(response) {
                    //TODO : Setting request name temporarily.
                    if(response.get('name') == null || response.get('name') == ''){
                    	response.set('name','Request');
                    }
                    APP.conversation.render(response);
                    ConversationEvents.triggerChange(response ? response.id : null);
                }
            });
		},

		render : function(pageNumber) {
			return this.renderActivityGroup();
		},

		 getColorCode : function(method){
            switch (method){
                case "GET" : return "blue";
                break;
                case "POST" : return "green";
                break;
                case "DELETE" : return "red";
                break;
                case "PUT" : return "orange";
                break;
            }
        },

		renderActivityGroup : function() {
			var that = this;
			var currentDate = moment(new Date());
			this.$el.html('');

            _.each(this.model, function (activity) {
                if(activity.lastModifiedDate){
                   var requestDiff = currentDate.diff(activity.lastModifiedDate,'hours');
                   if(requestDiff == 0){
                    activity.time = currentDate.diff(activity.lastModifiedDate,'minutes') + " min ago";
                   }else if(requestDiff < 24){
                    activity.time = requestDiff + ' hr ago';
                   }else{
                    activity.time = moment(activity.lastModifiedDate).format('MMM DD hh:mma');
                   }
                }
                if(activity.lastModifiedBy !== null){
                    activity.runBy = 'by '+ activity.lastModifiedBy.name;
                }
                activity.className = "lozenge left " + that.getColorCode(activity.rfRequestDTO.methodType) + " auth_required";
                var activityTemplate = that.template({conversation : activity});
                $(that.el).append(activityTemplate);
            }, this);

			return this;
		}
	});

var HistoryView = Backbone.View.extend({
	el: '#history-items',
	initialize : function() {

	},

	render : function(response) {
		this.$el.html('');

        var historyList = response.data;
        var totalPages = response.totalPages;
        var page = response.page;
        var limit = response.limit;

		this.model = historyList;

		var historyListItemView = new HistoryListItemView({model: this.model});

		this.$el.append('

');
		$("#activity-pannel").html(historyListItemView.render(1).el);

		$('.activity-paginator').bootpag({
            total: totalPages,
			page: 1,
			maxVisible: 5
		}).on("page", function(event, pageNumber){
            //fetch activity-log per page.
             var zeroBasedPageNumber = pageNumber - 1;
            $.ajax({
                url : APP.config.baseUrl + '/conversations?page='+zeroBasedPageNumber+'&limit=10',
                type : 'get',
                dataType : 'json',
                contentType : "application/json",
                success : function(response) {
                    var historyList = response.data;
                    historyListItemView = new HistoryListItemView({model: historyList});
                    $("#activity-pannel").html(historyListItemView.render(pageNumber).el);
                }
            });
		});
		return this;
	}
});

return HistoryView;

});
<commit_msg>Minor modifications<commit_after>define(function(require) {
	"use strict";

	var Backbone = require('backbone');
	var _ = require('underscore');
	var ConversationModel = require("models/conversation");
	var ConversationEvents = require('events/conversation-event');
	require('bootpag');
	require('moment');

	var HistoryListItemView = Backbone.View.extend({
		tagName : 'li',
		events : {
			"click a" : "renderConversationEvent"
		},
		template : _.template($('#tpl-history-list-item').html()),

		renderConversationEvent : function(event){
			var conversation = new ConversationModel({
				id : $(event.currentTarget).data('historyId')
			});
			conversation.fetch({
				success : function(response) {
                    //TODO : Setting request name temporarily.
                    if(response.get('name') == null || response.get('name') == ''){
                    	response.set('name','Request');
                    }
                    APP.conversation.render(response);
                    ConversationEvents.triggerChange(response ? response.id : null);
                }
            });
		},

		render : function(pageNumber) {
			return this.renderActivityGroup();
		},

		 getColorCode : function(method){
            switch (method){
                case "GET" : return "blue";
                break;
                case "POST" : return "green";
                break;
                case "DELETE" : return "red";
                break;
                case "PUT" : return "orange";
                break;
            }
        },

		renderActivityGroup : function() {
			var that = this;
			var currentDate = moment(new Date());
			this.$el.html('');

            _.each(this.model, function (activity) {
                if(activity.lastModifiedDate){
                   var requestDiff = currentDate.diff(activity.lastModifiedDate,'hours');
                   if(requestDiff == 0){
                       var min = currentDate.diff(activity.lastModifiedDate,'minutes')
                       if(min > 1){
                            activity.time = min + " minutes ago";
                       }
                       else{
                            activity.time = min + " minute ago";
                       }

                   }
                   else if(requestDiff <= 1){
                    activity.time = requestDiff + ' hour ago';
                   }
                   else if(requestDiff < 24){
                    activity.time = requestDiff + ' hours ago';
                   }
                   else{
                    activity.time = moment(activity.lastModifiedDate).format('MMM DD hh:mma');
                   }
                }
                if(activity.lastModifiedBy !== null){
                    activity.runBy = 'by '+ activity.lastModifiedBy.name;
                }
                activity.className = "lozenge left " + that.getColorCode(activity.rfRequestDTO.methodType) + " auth_required";
                var activityTemplate = that.template({conversation : activity});
                $(that.el).append(activityTemplate);
            }, this);

			return this;
		}
	});

var HistoryView = Backbone.View.extend({
	el: '#history-items',
	initialize : function() {

	},

	render : function(response) {
		this.$el.html('');

        var historyList = response.data;
        var totalPages = response.totalPages;
        var page = response.page;
        var limit = response.limit;

		this.model = historyList;

		var historyListItemView = new HistoryListItemView({model: this.model});

		this.$el.append('

');
		$("#activity-pannel").html(historyListItemView.render(1).el);

		$('.activity-paginator').bootpag({
            total: totalPages,
			page: 1,
			maxVisible: 5
		}).on("page", function(event, pageNumber){
            //fetch activity-log per page.
             var zeroBasedPageNumber = pageNumber - 1;
            $.ajax({
                url : APP.config.baseUrl + '/conversations?page='+zeroBasedPageNumber+'&limit=10',
                type : 'get',
                dataType : 'json',
                contentType : "application/json",
                success : function(response) {
                    var historyList = response.data;
                    historyListItemView = new HistoryListItemView({model: historyList});
                    $("#activity-pannel").html(historyListItemView.render(pageNumber).el);
                }
            });
		});
		return this;
	}
});

return HistoryView;

});
<|endoftext|>


<commit_before>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cola = require("webcola");
const d3 = require("d3");
/**
 * Function for updating webcola options.
 * Returns a new simulation and uses the defined layout variable.
 */
function updateColaLayout(layoutOptions) {
    let tempSimulation = cola.d3adaptor(d3)
        .size([layoutOptions.width, layoutOptions.height])
        .avoidOverlaps(layoutOptions.avoidOverlaps)
        .handleDisconnected(layoutOptions.handleDisconnected);
    // TODO: Work out what's up with the edge length.
    switch (layoutOptions.layoutType) {
        case "jaccardLinkLengths":
            // layoutOptions.edgeLength needs to be a number for jaccard to work.
            if (layoutOptions.edgeLength === undefined || typeof layoutOptions.edgeLength !== "number") {
                console.error("'edgeLength' needs to be set to a number for jaccardLinkLengths to work properly");
            }
            tempSimulation = tempSimulation.jaccardLinkLengths(layoutOptions.edgeLength, layoutOptions.jaccardModifier);
            break;
        case "flowLayout":
            if (layoutOptions.edgeLength === undefined || !(typeof layoutOptions.edgeLength === "number" || typeof layoutOptions.edgeLength === "function")) {
                console.error("'edgeLength' needs to be set to a number or function for flowLayout to work properly");
            }
            tempSimulation = tempSimulation.flowLayout(layoutOptions.flowDirection, layoutOptions.edgeLength);
            break;
        case "linkDistance":
        default:
            tempSimulation = tempSimulation.linkDistance(layoutOptions.edgeLength);
            break;
    }
    // Bind the nodes and links to the simulation
    return tempSimulation;
}
exports.updateColaLayout = updateColaLayout;
//# sourceMappingURL=updateColaLayout.js.map<commit_msg>save pinned node<commit_after>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cola = require("webcola");
const d3 = require("d3");
/**
 * Function for updating webcola options.
 * Returns a new simulation and uses the defined layout variable.
 */
function updateColaLayout(layoutOptions) {
    let tempSimulation = cola.d3adaptor(d3)
        .size([layoutOptions.width, layoutOptions.height])
        .linkDistance(20)
        .avoidOverlaps(layoutOptions.avoidOverlaps)
        .handleDisconnected(layoutOptions.handleDisconnected);
    // TODO: Work out what's up with the edge length.
    switch (layoutOptions.layoutType) {
        case "jaccardLinkLengths":
            // layoutOptions.edgeLength needs to be a number for jaccard to work.
            if (layoutOptions.edgeLength === undefined || typeof layoutOptions.edgeLength !== "number") {
                console.error("'edgeLength' needs to be set to a number for jaccardLinkLengths to work properly");
            }
            tempSimulation = tempSimulation.jaccardLinkLengths(layoutOptions.edgeLength, layoutOptions.jaccardModifier);
            break;
        case "flowLayout":
            if (layoutOptions.edgeLength === undefined || !(typeof layoutOptions.edgeLength === "number" || typeof layoutOptions.edgeLength === "function")) {
                console.error("'edgeLength' needs to be set to a number or function for flowLayout to work properly");
            }
            tempSimulation = tempSimulation.flowLayout(layoutOptions.flowDirection, layoutOptions.edgeLength);
            break;
        case "linkDistance":
        default:
            tempSimulation = tempSimulation.linkDistance(layoutOptions.edgeLength);
            break;
    }
    // Bind the nodes and links to the simulation
    return tempSimulation;
}
exports.updateColaLayout = updateColaLayout;
//# sourceMappingURL=updateColaLayout.js.map<|endoftext|>