<commit_before>/**
 * @Description: GridGallery is a tiny package that will generate a grid depending on
 *               the elements height. It is not required to have the same height
 *
 * @Author:      Mohamed Hassan
 * @Author Url:  http://mohamedhassan.me
 *
 * @License:     under MIT
 *               https://github.com/pencilpix/grid-gallery/blob/master/LICENSE
 */
((name, definition) => {
  let theModule  = definition(),
      hasDefine  = typeof define === 'function' && define.amd,
      hasExports = typeof module !== 'undefined' && module.exports;

  if(hasDefine)
    define(theModule);
  else if(hasExports)
    module.exports = theModule;
  else
    window[name] = theModule;

})('GridGallery', () => {
  const VERSION = '1.0.1';

  /**
   * default options
   *
   * @type {Object}
   */
  const DEFAULTS = {
    direction: 'left',
  };

  /**
   * GridGallery generates a grid that its
   * item it's not required to be in the same height
   *
   * @param {HTMLElement}  element  grid container element
   * @param {Object}       options  custom options
   */
  class GridGallery {
    constructor( element, options ) {
      this.element = element;
      this.options = Object.assign({}, GridGallery.DEFAULTS, options);
      this.rows = [];

      this._timeout = null;
      this._delay = 300;
      this._boundResizeHandler = this._resizeHandler.bind(this);

      this.init();
    }

    init() {
      this.updateGridRows();
      this.updatePositions();

      window.addEventListener('resize', this._boundResizeHandler);
    }

    update() {
      this.rows = [];
      this.updateGridRows();
      this.updatePositions();
    }

    /**
     * get rows of the grid depending on current
     * container children and it's order
     */
    updateGridRows() {
      [...this.element.children].forEach((item, i) => {
        let index = i % this.maxItemsPerRow;
        let position;
        if ( index === 0){
          this.rows.push([]);
        }

        position = this.getItemPosition(index);
        this.rows[this.lastIndex].push({item: item, position: position});
      });
    }

    /**
     * calculate the position of an element depending on it's
     * position on the grid.
     *
     * @param {Number}  index  the number reperesent index in current row
     * @return {Object}
     */
    getItemPosition(index) {
      let direction = this.options.direction;
      let lastIndex = this.lastIndex;
      let rowIs     = lastIndex === 0 ? 'first_row' : 'any_row';
      let itemIs    = index === 0 ? 'first_item' : 'any_item';

      let position  = {};
      let prevItem, prevRowItem;

      switch (rowIs + '_and_' + itemIs) {
        case 'first_row_and_first_item':
          position.top = 0;
          position[direction] = this.remainSpace;
          break;

        case 'first_row_and_any_item':
          prevItem = this.rows[lastIndex][index - 1];
          position.top = 0;
          position[direction] = prevItem.position[direction] + prevItem.item.offsetWidth;
          break;

        case 'any_row_and_first_item':
          prevRowItem = this.rows[lastIndex - 1][index];
          position.top = prevRowItem.position.top + prevRowItem.item.offsetHeight;
          position[direction] = this.remainSpace;
          break;

        case 'any_row_and_any_item':
          prevItem = this.rows[lastIndex][index - 1];
          prevRowItem = this.rows[lastIndex - 1][index];
          position.top = prevRowItem.position.top + prevRowItem.item.offsetHeight;
          position[direction] = prevItem.position[direction] + prevItem.item.offsetWidth;
          break;
      }

      return position;
    }

    /**
     * update the position of each item
     * depending on position iformation
     * stored in item object of in rows property
     */
    updatePositions() {
      let direction = this.options.direction;
      if(this.lastIndex === -1)
        return;

      this.rows.forEach(row => {
        row.forEach(rowItem => {
          let itemBottom = rowItem.position.top + rowItem.item.offsetHeight;
          rowItem.item.style.top = rowItem.position.top + 'px';
          rowItem.item.style[direction] = rowItem.position[direction] + 'px';
          if(this.element.offsetHeight < itemBottom)
              this.element.style.height = itemBottom + 'px';
        });
      });
    }

    _resizeHandler() {
      let start = Date.now();
      clearTimeout(this._timeout);

      this._timeout = setTimeout(() => {
        if(this.itemWidth)
          this.update();
      }, this._delay);
    }

    /**
     * Getter: calculate first item width.
     *
     * @return {Number}
     */
    get itemWidth() {
      return this.element.children[0].offsetWidth;
    }

    /**
     * Getter: calculate the maximum number
     * of elements can be positioned in one row.
     *
     * @return {Number}
     */
    get maxItemsPerRow() {
      let containerWidth = this.element.offsetWidth;
      return Math.floor(containerWidth / this.itemWidth);
    }

    /**
     * Getter: calculate the remaining space after adding items in rows
     * and return its half to be used as margin 'centering the items'
     *
     * @return {Number}
     */
    get remainSpace() {
      let containerWidth = this.element.offsetWidth;
      let itemsWidth = this.maxItemsPerRow * this.itemWidth

      return Math.floor((containerWidth - itemsWidth) / 2);
    }

    /**
     * Getter: calculate last row index in grid
     *
     * @return {Number}
     */
    get lastIndex() {
      return this.rows.length - 1;
    }

    /**
     * Getter: check for current direction of document
     * and update and return default options.
     *
     * @return {Object}
     */
    static get DEFAULTS () {
      if(document.documentElement.dir === 'rtl')
        DEFAULTS.direction = 'right';
      else
        DEFAULTS.direction = 'left';

      return DEFAULTS;
    }
  }

  return GridGallery;
});

<commit_msg>Return max number of items 1 if item width bigger than container's<commit_after>/**
 * @Description: GridGallery is a tiny package that will generate a grid depending on
 *               the elements height. It is not required to have the same height
 *
 * @Author:      Mohamed Hassan
 * @Author Url:  http://mohamedhassan.me
 *
 * @License:     under MIT
 *               https://github.com/pencilpix/grid-gallery/blob/master/LICENSE
 */
((name, definition) => {
  let theModule  = definition(),
      hasDefine  = typeof define === 'function' && define.amd,
      hasExports = typeof module !== 'undefined' && module.exports;

  if(hasDefine)
    define(theModule);
  else if(hasExports)
    module.exports = theModule;
  else
    window[name] = theModule;

})('GridGallery', () => {
  const VERSION = '1.0.1';

  /**
   * default options
   *
   * @type {Object}
   */
  const DEFAULTS = {
    direction: 'left',
  };

  /**
   * GridGallery generates a grid that its
   * item it's not required to be in the same height
   *
   * @param {HTMLElement}  element  grid container element
   * @param {Object}       options  custom options
   */
  class GridGallery {
    constructor( element, options ) {
      this.element = element;
      this.options = Object.assign({}, GridGallery.DEFAULTS, options);
      this.rows = [];

      this._timeout = null;
      this._delay = 300;
      this._boundResizeHandler = this._resizeHandler.bind(this);

      this.init();
    }

    init() {
      this.updateGridRows();
      this.updatePositions();

      window.addEventListener('resize', this._boundResizeHandler);
    }

    update() {
      this.rows = [];
      this.updateGridRows();
      this.updatePositions();
    }

    /**
     * get rows of the grid depending on current
     * container children and it's order
     */
    updateGridRows() {

      [...this.element.children].forEach((item, i) => {
        let index = i % this.maxItemsPerRow;
        let position;
        if ( index === 0){
          this.rows.push([]);
        }

        position = this.getItemPosition(index);
        this.rows[this.lastIndex].push({item: item, position: position});
      });
    }

    /**
     * calculate the position of an element depending on it's
     * position on the grid.
     *
     * @param {Number}  index  the number reperesent index in current row
     * @return {Object}
     */
    getItemPosition(index) {
      let direction = this.options.direction;
      let lastIndex = this.lastIndex;
      let rowIs     = lastIndex === 0 ? 'first_row' : 'any_row';
      let itemIs    = index === 0 ? 'first_item' : 'any_item';

      let position  = {};
      let prevItem, prevRowItem;

      switch (rowIs + '_and_' + itemIs) {
        case 'first_row_and_first_item':
          position.top = 0;
          position[direction] = this.remainSpace;
          break;

        case 'first_row_and_any_item':
          prevItem = this.rows[lastIndex][index - 1];
          position.top = 0;
          position[direction] = prevItem.position[direction] + prevItem.item.offsetWidth;
          break;

        case 'any_row_and_first_item':
          prevRowItem = this.rows[lastIndex - 1][index];
          position.top = prevRowItem.position.top + prevRowItem.item.offsetHeight;
          position[direction] = this.remainSpace;
          break;

        case 'any_row_and_any_item':
          prevItem = this.rows[lastIndex][index - 1];
          prevRowItem = this.rows[lastIndex - 1][index];
          position.top = prevRowItem.position.top + prevRowItem.item.offsetHeight;
          position[direction] = prevItem.position[direction] + prevItem.item.offsetWidth;
          break;
      }

      return position;
    }

    /**
     * update the position of each item
     * depending on position iformation
     * stored in item object of in rows property
     */
    updatePositions() {
      let direction = this.options.direction;
      if(this.lastIndex === -1)
        return;

      this.rows.forEach(row => {
        row.forEach(rowItem => {
          let itemBottom = rowItem.position.top + rowItem.item.offsetHeight;
          rowItem.item.style.top = rowItem.position.top + 'px';
          rowItem.item.style[direction] = rowItem.position[direction] + 'px';
          if(this.element.offsetHeight < itemBottom)
              this.element.style.height = itemBottom + 'px';
        });
      });
    }

    _resizeHandler() {
      let start = Date.now();
      clearTimeout(this._timeout);

      this._timeout = setTimeout(() => {
        if(this.itemWidth)
          this.update();
      }, this._delay);
    }

    /**
     * Getter: calculate first item width.
     *
     * @return {Number}
     */
    get itemWidth() {
      return this.element.children[0].offsetWidth;
    }

    /**
     * Getter: calculate the maximum number
     * of elements can be positioned in one row.
     *
     * @return {Number}
     */
    get maxItemsPerRow() {
      let containerWidth = this.element.offsetWidth;
      let count = Math.floor(containerWidth / this.itemWidth);

      if(count > 0)
        return count;
      else
        return 1;
    }

    /**
     * Getter: calculate the remaining space after adding items in rows
     * and return its half to be used as margin 'centering the items'
     *
     * @return {Number}
     */
    get remainSpace() {
      let containerWidth = this.element.offsetWidth;
      let itemsWidth = this.maxItemsPerRow * this.itemWidth

      return Math.floor((containerWidth - itemsWidth) / 2);
    }

    /**
     * Getter: calculate last row index in grid
     *
     * @return {Number}
     */
    get lastIndex() {
      return this.rows.length - 1;
    }

    /**
     * Getter: check for current direction of document
     * and update and return default options.
     *
     * @return {Object}
     */
    static get DEFAULTS () {
      if(document.documentElement.dir === 'rtl')
        DEFAULTS.direction = 'right';
      else
        DEFAULTS.direction = 'left';

      return DEFAULTS;
    }
  }

  return GridGallery;
});

<|endoftext|>


<commit_before>(function($, undefined) {

$.widget( "mswin.window", {
    _create: function() {
        this.element.resizable({ handles: "all" });
        this.element.draggable({ handle: ".title" });
        this._on({
            "click .title-button.maximize": function( event ) {
                this.maximize();
            },
            "click .title-button.restore": function( event ) {
                this.restore();
            },
            "click .title-button.close": function( event ) {
                this.element.hide();
            },
            "dblclick .title": function( event ) {
                if (this.element.hasClass( "maximized" )) {
                    this.restore();
                }
                else {
                    this.maximize();
                }
            },
        });
        $(window).resize(function() {
            this.resize();
        });
        if (this.element.hasClass( "maximized" )) {
            this.maximize();
        }
        else {
            this.restore();
        }
    },

    maximize: function() {
        // TODO: animation
        this._offset = this.element.offset();
        this._width = this.element.width();
        this._height = this.element.height();
        this.element
            .draggable( "disable" )
            .addClass( "maximized" )
            .css({
                left: "auto",
                top: "0",
                width: "100%",
                height: "auto",
            });
        this.element.find( ".title-button.maximize" )
            .removeClass( "maximize" )
            .addClass( "restore" );
        this.resize();
    },

    restore: function() {
        // TODO: animation
        this.element
            .removeClass( "maximized" )
            .draggable( "enable" )
            .css({ bottom: "auto" })
            .offset( this._offset )
            .width( this._width )
            .height( this._height );
        this.element.find( ".title-button.restore" )
            .removeClass( "restore" )
            .addClass( "maximize" );
    },

    resize: function() {
        if (this.element.hasClass( "maximized" )) {
            var taskbar_height = $( ".taskbar" ).height();
            this.element.css({
                bottom: taskbar_height + "px",
            });
        }
    },
});

}(jQuery));
<commit_msg>js: bind this<commit_after>(function($, undefined) {

$.widget( "mswin.window", {
    _create: function() {
        this.element.resizable({ handles: "all" });
        this.element.draggable({ handle: ".title" });
        this._on({
            "click .title-button.maximize": function( event ) {
                this.maximize();
            },
            "click .title-button.restore": function( event ) {
                this.restore();
            },
            "click .title-button.close": function( event ) {
                this.element.hide();
            },
            "dblclick .title": function( event ) {
                if (this.element.hasClass( "maximized" )) {
                    this.restore();
                }
                else {
                    this.maximize();
                }
            },
        });
        $(window).resize($.proxy(function() {
            this.resize();
        }, this));
        if (this.element.hasClass( "maximized" )) {
            this.maximize();
        }
        else {
            this.restore();
        }
    },

    maximize: function() {
        // TODO: animation
        this._offset = this.element.offset();
        this._width = this.element.width();
        this._height = this.element.height();
        this.element
            .draggable( "disable" )
            .addClass( "maximized" )
            .css({
                left: "auto",
                top: "0",
                width: "100%",
                height: "auto",
            });
        this.element.find( ".title-button.maximize" )
            .removeClass( "maximize" )
            .addClass( "restore" );
        this.resize();
    },

    restore: function() {
        // TODO: animation
        this.element
            .removeClass( "maximized" )
            .draggable( "enable" )
            .css({ bottom: "auto" })
            .offset( this._offset )
            .width( this._width )
            .height( this._height );
        this.element.find( ".title-button.restore" )
            .removeClass( "restore" )
            .addClass( "maximize" );
    },

    resize: function() {
        if (this.element.hasClass( "maximized" )) {
            var taskbar_height = $( ".taskbar" ).height();
            this.element.css({
                bottom: taskbar_height + "px",
            });
        }
    },
});

}(jQuery));
<|endoftext|>


<commit_before>angular.module('jkuri.datepicker', [])

.directive('ngDatepicker', ['$document', function($document) {
	'use strict';

	var setScopeValues = function (scope, attrs) {
		scope.format = attrs.format || 'YYYY-MM-DD';
		scope.viewFormat = attrs.viewFormat || 'Do MMMM YYYY';
		scope.locale = attrs.locale || 'en';
		scope.firstWeekDaySunday = scope.$eval(attrs.firstWeekDaySunday) || false;
		scope.placeholder = attrs.placeholder || '';
	};

	return {
		restrict: 'EA',
		require: '?ngModel',
		link: function (scope, element, attrs, ngModel) {
			setScopeValues(scope, attrs);

			scope.calendarOpened = false;
			scope.days = [];
			scope.dayNames = [];
			scope.viewValue = null;
			scope.dateValue = null;

			moment.locale(scope.locale);
			var date = moment();

			var generateCalendar = function (date) {
				var lastDayOfMonth = date.endOf('month').date(),
					month = date.month(),
					year = date.year(),
					n = 1;

				var firstWeekDay = scope.firstWeekDaySunday === true ? date.set('date', 2).day() : date.set('date', 1).day();
				if (firstWeekDay !== 1) {
					n -= firstWeekDay - 1;
				}

				scope.dateValue = date.format('MMMM YYYY');
				scope.days = [];

				for (var i = n; i <= lastDayOfMonth; i += 1) {
					if (i > 0) {
						scope.days.push({day: i, month: month + 1, year: year, enabled: true});
					} else {
						scope.days.push({day: null, month: null, year: null, enabled: false});
					}
				}
			};

			var generateDayNames = function () {
				var date = scope.firstWeekDaySunday === true ?  moment('2015-06-07') : moment('2015-06-01');
				for (var i = 0; i < 7; i += 1) {
					scope.dayNames.push(date.format('ddd'));
					date.add('1', 'd');
				}
			};

			generateDayNames();

			scope.showCalendar = function () {
				scope.calendarOpened = true;
				generateCalendar(date);
			};

			scope.closeCalendar = function () {
				scope.calendarOpened = false;
			};

			scope.prevYear = function () {
				date.subtract(1, 'Y');
				generateCalendar(date);
			};

			scope.prevMonth = function () {
				date.subtract(1, 'M');
				generateCalendar(date);
			};

			scope.nextMonth = function () {
				date.add(1, 'M');
				generateCalendar(date);
			};

			scope.nextYear = function () {
				date.add(1, 'Y');
				generateCalendar(date);
			};

			scope.selectDate = function (event, date) {
				event.preventDefault();
				var selectedDate = moment(date.day + '.' + date.month + '.' + date.year, 'DD.MM.YYYY');
				ngModel.$setViewValue(selectedDate.format(scope.format));
				scope.viewValue = selectedDate.format(scope.viewFormat);
				scope.closeCalendar();
			};

			// if clicked outside of calendar
			var classList = ['ng-datepicker', 'ng-datepicker-input'];
            if (attrs.id !== undefined) classList.push(attrs.id);
			$document.on('click', function (e) {
				if (!scope.calendarOpened) return;

				var i = 0,
					element;

				if (!e.target) return;

				for (element = e.target; element; element = element.parentNode) {
					var id = element.id;
					var classNames = element.className;

					if (id !== undefined) {
						for (i = 0; i < classList.length; i += 1) {
							if (id.indexOf(classList[i]) > -1 || classNames.indexOf(classList[i]) > -1) {
								return;
							}
						}
					}
				}

				scope.closeCalendar();
				scope.$apply();
			});

			ngModel.$render = function () {
				var newValue = ngModel.$viewValue;
				scope.viewValue = moment(newValue).format(attrs.viewFormat);
				scope.dateValue = newValue;
			};

		},
		template:
		'
<input type="text" ng-focus="showCalendar()" ng-value="viewValue" class="ng-datepicker-input" placeholder="{{ placeholder }}">
' +
		'
' +
		'
' +
		'
' +
		'      ' +
		'      ' +
		'
' +
		'    ' +
		'
' +
		'      ' +
		'      ' +
		'
' +
		'
' +
		'
' +
		'    ' +
		'      {{ dn }}' +
		'    ' +
		'
' +
		'
' +
		'    ' +
		'      {{ d.day }}' +
		'    ' +
		'
' +
		'
'
	};

}]);

<commit_msg>Fix isolated scope in directive<commit_after>angular.module('jkuri.datepicker', [])

.directive('ngDatepicker', ['$document', function($document) {
	'use strict';

	var setScopeValues = function (scope, attrs) {
		scope.format = attrs.format || 'YYYY-MM-DD';
		scope.viewFormat = attrs.viewFormat || 'Do MMMM YYYY';
		scope.locale = attrs.locale || 'en';
		scope.firstWeekDaySunday = scope.$eval(attrs.firstWeekDaySunday) || false;
		scope.placeholder = attrs.placeholder || '';
	};

	return {
		restrict: 'EA',
		require: '?ngModel',
		scope: {},
		link: function (scope, element, attrs, ngModel) {
			setScopeValues(scope, attrs);

			scope.calendarOpened = false;
			scope.days = [];
			scope.dayNames = [];
			scope.viewValue = null;
			scope.dateValue = null;

			moment.locale(scope.locale);
			var date = moment();

			var generateCalendar = function (date) {
				var lastDayOfMonth = date.endOf('month').date(),
					month = date.month(),
					year = date.year(),
					n = 1;

				var firstWeekDay = scope.firstWeekDaySunday === true ? date.set('date', 2).day() : date.set('date', 1).day();
				if (firstWeekDay !== 1) {
					n -= firstWeekDay - 1;
				}

				scope.dateValue = date.format('MMMM YYYY');
				scope.days = [];

				for (var i = n; i <= lastDayOfMonth; i += 1) {
					if (i > 0) {
						scope.days.push({day: i, month: month + 1, year: year, enabled: true});
					} else {
						scope.days.push({day: null, month: null, year: null, enabled: false});
					}
				}
			};

			var generateDayNames = function () {
				var date = scope.firstWeekDaySunday === true ?  moment('2015-06-07') : moment('2015-06-01');
				for (var i = 0; i < 7; i += 1) {
					scope.dayNames.push(date.format('ddd'));
					date.add('1', 'd');
				}
			};

			generateDayNames();

			scope.showCalendar = function () {
				scope.calendarOpened = true;
				generateCalendar(date);
			};

			scope.closeCalendar = function () {
				scope.calendarOpened = false;
			};

			scope.prevYear = function () {
				date.subtract(1, 'Y');
				generateCalendar(date);
			};

			scope.prevMonth = function () {
				date.subtract(1, 'M');
				generateCalendar(date);
			};

			scope.nextMonth = function () {
				date.add(1, 'M');
				generateCalendar(date);
			};

			scope.nextYear = function () {
				date.add(1, 'Y');
				generateCalendar(date);
			};

			scope.selectDate = function (event, date) {
				event.preventDefault();
				var selectedDate = moment(date.day + '.' + date.month + '.' + date.year, 'DD.MM.YYYY');
				ngModel.$setViewValue(selectedDate.format(scope.format));
				scope.viewValue = selectedDate.format(scope.viewFormat);
				scope.closeCalendar();
			};

			// if clicked outside of calendar
			var classList = ['ng-datepicker', 'ng-datepicker-input'];
            if (attrs.id !== undefined) classList.push(attrs.id);
			$document.on('click', function (e) {
				if (!scope.calendarOpened) return;

				var i = 0,
					element;

				if (!e.target) return;

				for (element = e.target; element; element = element.parentNode) {
					var id = element.id;
					var classNames = element.className;

					if (id !== undefined) {
						for (i = 0; i < classList.length; i += 1) {
							if (id.indexOf(classList[i]) > -1 || classNames.indexOf(classList[i]) > -1) {
								return;
							}
						}
					}
				}

				scope.closeCalendar();
				scope.$apply();
			});

			ngModel.$render = function () {
				var newValue = ngModel.$viewValue;
				scope.viewValue = moment(newValue).format(attrs.viewFormat);
				scope.dateValue = newValue;
			};

		},
		template:
		'
<input type="text" ng-focus="showCalendar()" ng-value="viewValue" class="ng-datepicker-input" placeholder="{{ placeholder }}">
' +
		'
' +
		'
' +
		'
' +
		'      ' +
		'      ' +
		'
' +
		'    ' +
		'
' +
		'      ' +
		'      ' +
		'
' +
		'
' +
		'
' +
		'    ' +
		'      {{ dn }}' +
		'    ' +
		'
' +
		'
' +
		'    ' +
		'      {{ d.day }}' +
		'    ' +
		'
' +
		'
'
	};

}]);

<|endoftext|>


<commit_before>var numeral = require('numeral'),
    i18n = require('i18n').module('ember_number_field', require.resolve('../locales')),
    t = i18n.t;

module.exports = require('ember-text-field').extend({

    align: 'right',
    autocomplete: 'off',

    inputType: 'number',

    min: null,
    minIncluded: true,
    max: null,
    maxIncluded: true,

    init: function() {
        this._super();
        var min = this.get('min'),
            max = this.get('max');
        if (min && !(typeof min == 'number')) {
            this.set('min', 1*min);
        }
        if (max && !(typeof max == 'number')) {
            this.set('max', 1*max);
        }
    },

    format: '0,0',
    _value: null,
    formatInputValue: function(value) {
        return Em.isEmpty(value) ? '' : numeral(value).format(this.get('format'));
    },
    unformatInputValue: function(inputValue) {
        return (Em.isEmpty(inputValue) || !this.isValidNumberString(inputValue)) ? null : numeral().unformat(numeral(numeral().unformat(inputValue)).format(this.get('format')));
    },
    validateInputValue: function(inputValue) {
        if (!Em.isEmpty(inputValue)) {
            if (!this.isValidNumberString(inputValue)) {
                throw new UserError(t('invalid_number'));
            }
            var value = this.unformatInputValue(inputValue),
                min = this.get('min'),
                minIncluded = this.get('minIncluded'),
                max = this.get('max'),
                maxIncluded = this.get('maxIncluded');
            if (!Em.isEmpty(min)) {
                if (minIncluded && value < min) {
                    throw new UserError(t('must_be_greater_equal', {number: this.formatInputValue(min)}));
                }
                if (!minIncluded && value <= min) {
                    throw new UserError(t('must_be_greater', {number: this.formatInputValue(min)}));
                }
            }
            if (!Em.isEmpty(max)) {
                if (maxIncluded && value > max) {
                    throw new UserError(t('must_be_less_equal', {number: this.formatInputValue(max)}));
                }
                if (!maxIncluded && value >= max) {
                    throw new UserError(t('must_be_less', {number: this.formatInputValue(min)}));
                }
            }
        }
    },
    isValidNumberString: function(value) {
        return value.match(/^-?[\d,]+(\.\d+)?$/);
    }
});

module.exports.lang = i18n.lang;<commit_msg>use inputmode=numeric instead of inputType=number<commit_after>var numeral = require('numeral'),
    i18n = require('i18n').module('ember_number_field', require.resolve('../locales')),
    t = i18n.t;

module.exports = require('ember-text-field').extend({

    align: 'right',
    autocomplete: 'off',

    inputmode: 'numeric',

    min: null,
    minIncluded: true,
    max: null,
    maxIncluded: true,

    init: function() {
        this._super();
        var min = this.get('min'),
            max = this.get('max');
        if (min && !(typeof min == 'number')) {
            this.set('min', 1*min);
        }
        if (max && !(typeof max == 'number')) {
            this.set('max', 1*max);
        }
    },

    format: '0,0',
    _value: null,
    formatInputValue: function(value) {
        return Em.isEmpty(value) ? '' : numeral(value).format(this.get('format'));
    },
    unformatInputValue: function(inputValue) {
        return (Em.isEmpty(inputValue) || !this.isValidNumberString(inputValue)) ? null : numeral().unformat(numeral(numeral().unformat(inputValue)).format(this.get('format')));
    },
    validateInputValue: function(inputValue) {
        if (!Em.isEmpty(inputValue)) {
            if (!this.isValidNumberString(inputValue)) {
                throw new UserError(t('invalid_number'));
            }
            var value = this.unformatInputValue(inputValue),
                min = this.get('min'),
                minIncluded = this.get('minIncluded'),
                max = this.get('max'),
                maxIncluded = this.get('maxIncluded');
            if (!Em.isEmpty(min)) {
                if (minIncluded && value < min) {
                    throw new UserError(t('must_be_greater_equal', {number: this.formatInputValue(min)}));
                }
                if (!minIncluded && value <= min) {
                    throw new UserError(t('must_be_greater', {number: this.formatInputValue(min)}));
                }
            }
            if (!Em.isEmpty(max)) {
                if (maxIncluded && value > max) {
                    throw new UserError(t('must_be_less_equal', {number: this.formatInputValue(max)}));
                }
                if (!maxIncluded && value >= max) {
                    throw new UserError(t('must_be_less', {number: this.formatInputValue(min)}));
                }
            }
        }
    },
    isValidNumberString: function(value) {
        return value.match(/^-?[\d,]+(\.\d+)?$/);
    }
});

module.exports.lang = i18n.lang;<|endoftext|>


<commit_before>function makeParallelSets(data, states, years, variables, target, width, height) {
    if(states.length != years.length) return console.error("states and years must be of equal length!");
    if(variables.length == 0) return console.error("you must provide at least one variable!");

    var culturals = ["jazz", "classical", "opera", "musical", "play", "ballet", "dance", "artmuseum", "park", "books"];

    var chart = d3.parsets()
        .dimensions(variables)
        .width(width)
        .height(height);

    var vis = target.append("svg")
        .attr("width", chart.width())
        .attr("height", chart.height());

    temp = [];

    for(var i = 0; i < states.length; i++) {
        data.forEach(function(state) {
            if (state.key == states[i]) {
                state.values.forEach(function(year) {
                    if (year.key == years[i]) {
                        temp.push(year.values);
                    }
                });
            }
        })
    }

    var data2 = [];
    temp.forEach(function (value) {
        $.merge(data2, value);
    });

    variables.forEach(function(cat) {
        if(culturals.indexOf(cat) != -1) {
            data2 = data2.filter(function(d) { return d[cat] == "yes" || d[cat] == "no"; });
        }
    });

    vis.datum(data2).call(chart);
}
<commit_msg>error catching for parallel sets<commit_after>function makeParallelSets(data, states, years, variables, target, width, height) {
    if(states.length != years.length) return console.error("states and years must be of equal length!");
    if(variables.length < 2) return console.error("you must provide at least two variables!");

    var culturals = ["jazz", "classical", "opera", "musical", "play", "ballet", "dance", "artmuseum", "park", "books"];

    var chart = d3.parsets()
        .dimensions(variables)
        .width(width)
        .height(height);

    var vis = target.append("svg")
        .attr("width", chart.width())
        .attr("height", chart.height());

    temp = [];

    for(var i = 0; i < states.length; i++) {
        data.forEach(function(state) {
            if (state.key == states[i]) {
                state.values.forEach(function(year) {
                    if (year.key == years[i]) {
                        temp.push(year.values);
                    }
                });
            }
        })
    }

    var data2 = [];
    temp.forEach(function (value) {
        $.merge(data2, value);
    });

    variables.forEach(function(cat) {
        if(culturals.indexOf(cat) != -1) {
            data2 = data2.filter(function(d) { return d[cat] == "yes" || d[cat] == "no"; });
        }
    });

    vis.datum(data2).call(chart);
}
<|endoftext|>


<commit_before>
import React from 'react'
import PropTypes from 'prop-types'
import keycode from 'keycode'
import classnames from 'classnames'

const PADDING_LEFT = 16
const LIST_ITEM_HEIGHT = 48

// list length
const MAX_LIST_LENGTH = 5

export default class Select extends React.Component {
  static propTypes = {
    disabled: PropTypes.bool,
    label: PropTypes.string,
    options: PropTypes.array,
    placeholder: PropTypes.string,
    onChange: PropTypes.func.isRequired,
    name: PropTypes.string
  }

  static defaultProps = {
    options: [
      {value: 'one', label: 'one'},
      {value: 'two', label: 'two'},
      {value: 'three', label: 'three'}
    ],
    placeholder: 'Placeholder',
    value: ''
  }

  state = {
    open: false
  }

  onKeyDown = event => {
    if (event.which === keycode('enter') || event.which === keycode('space')) {
      event.preventDefault()
      this.open()
      return
    }
    if (event.which === keycode('up') || event.which === keycode('left')) {
      event.preventDefault()
      const {options, value} = this.props
      const i = options.findIndex(option => option.value === value)
      if (i > 0) {
        const prev = options[i - 1]
        return this.props.onChange({
          target: {
            name: this.props.name,
            ...prev
          }
        })
      }
    }
    if (event.which === keycode('down') || event.which === keycode('right')) {
      event.preventDefault()
      const {options, value} = this.props
      const i = options.findIndex(option => option.value === value)
      if (i < options.length - 1) {
        const next = options[i + 1]
        return this.props.onChange({
          target: {
            name: this.props.name,
            ...next
          }
        })
      }
    }
  }

  open = () => {
    if (this.props.disabled) { return }
    this.setState({
      open: true
    })
    document.addEventListener('click', this.close)
  }

  close = () => {
    this.setState({
      open: false
    })
    document.removeEventListener('click', this.close)
  }

  findTableTag = (node) => {
    while (node.parentNode) {
      node = node.parentNode
      if (node.tagName === 'TABLE') {
        return true
      }
    }
    return false
  }

  componentDidMount () {
    const isInsideTable = this.findTableTag(this.refWrapper)
    this.setState({
      isInsideTable
    })
  }

  onChange = (item) => {
    this.props.onChange({
      target: {
        name: this.props.name,
        ...item
      }
    })
  }

  onEnter = item => {
    this.props.onChange({
      target: {
        name: this.props.name,
        ...item
      }
    })
    this.onEscape()
  }

  onEscape = () => {
    this.close()
    this.refInput.focus()
  }

  shouldComponentUpdate (nextProps, nextState) {
    if (this.state.open && nextState.open) {
      return false
    }
    return true
  }

  render () {
    const selectedIndex = this.props.options.findIndex(option => option.value === this.props.value)
    const empty = selectedIndex === -1
    const text = empty ? this.props.placeholder : this.props.options[selectedIndex].label

    return (

 { this.refWrapper = c }}
      >
        <input
          className='mdc-Select-input'
          name={this.props.name}
          value={this.props.value}
          disabled={this.props.disabled}
          onKeyDown={this.onKeyDown}
          ref={elem => { this.refInput = elem }}
          readOnly
        />
        {
          this.props.label && {this.props.label}
        }

            {text}

        {
          this.state.open &&
          <List
            options={this.props.options}
            selectedIndex={selectedIndex}
            onClick={this.onChange}
            onEnter={this.onEnter}
            refWrapper={this.refWrapper}
            isInsideTable={this.state.isInsideTable}
            onEscape={this.onEscape}
          />
        }

    )
  }
}

export class List extends React.Component {
  static propTypes = {
    options: PropTypes.array.isRequired,
    isInsideTable: PropTypes.bool,
    selectedIndex: PropTypes.number.isRequired,
    onClick: PropTypes.func.isRequired,
    refWrapper: PropTypes.object.isRequired
  }

  state = {
    left: this.props.refWrapper.getBoundingClientRect().left,
    top: this.props.refWrapper.getBoundingClientRect().top,
    width: this.props.refWrapper.getBoundingClientRect().width
  }

  componentDidMount () {
    const index = this.props.selectedIndex

    // create boolean helper variables
    const scrollable = this.props.options.length > MAX_LIST_LENGTH
    const indexWithinFirstTwoItems = index < 2

    if (scrollable && !indexWithinFirstTwoItems) {
      const scrollTop = (LIST_ITEM_HEIGHT * (index - 2))
      this.ref.scrollTop = scrollTop
    }

    const focus = index >= 0 ? index : 0
    this[`li${focus}`].focus()

    window.addEventListener('resize', this.resize)
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.resize)
  }

  resize = () => {
    const {left, top, width} = this.props.refWrapper.getBoundingClientRect()
    this.setState({
      left,
      top,
      width
    })
  }

  onClick = event => {
    const index = parseInt(event.currentTarget.getAttribute('data-id'))
    this.props.onClick(this.props.options[index])
  }

  onBlur = event => {
    // close list when focus is outside of list
    if (event.relatedTarget && !event.relatedTarget.classList.contains('mdc-Select-listItem')) {
      this.props.onEscape()
    }
  }

  onKeyDown = event => {
    const index = parseInt(event.currentTarget.getAttribute('data-id'))
    if (event.which === keycode('enter')) {
      return this.props.onEnter(this.props.options[index])
    }
    if (event.which === keycode('escape')) {
      return this.props.onEscape()
    }
    if (event.which === keycode('down')) {
      event.preventDefault()
      if (event.target.nextSibling) {
        return event.target.nextSibling.focus()
      }
    }
    if (event.which === keycode('up')) {
      event.preventDefault()
      if (event.target.previousSibling) {
        return event.target.previousSibling.focus()
      }
    }
  }

  render () {
    // CSS space
    let PADDING_TOP = -22
    if (this.props.isInsideTable) {
      // when select component is inside a table cell we have to remove
      // border bottom, padding top and padding bottom.
      // this changes the location of the text.
      // that leads to the list menu / overlay no being directly on top of the text.
      // we therefore have to modify the padding top to fix the overlay position.
      PADDING_TOP = 24
    }

    const {options, selectedIndex} = this.props

    // handle list absolute position top
    const paddingTop = PADDING_TOP

    let top
    if (selectedIndex === -1) {
      // set position to first element, i.e. selectedIndex = 0
      top = -1 * paddingTop
    } else {
      top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * selectedIndex))
    }

    // handle scrollable lists with more than 5 list items
    if (options.length > MAX_LIST_LENGTH) {
      if (selectedIndex >= 2 && selectedIndex <= options.length - 3) {
        // handle "center" items => always set to third position
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 2))
      } else if (selectedIndex === options.length - 2) {
        // handle second last item
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 3))
      } else if (selectedIndex === options.length - 1) {
        // handle last item
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 4))
      }
    }

    let width = this.state.width + (2 * PADDING_LEFT)
    let left = this.props.isInsideTable ? -17 : -16
    let padding = 16

    // check if select overlay is wider than window which would cause horizontal overflow
    // if so decrease padding left and right from 16px to 8px
    // adjust absolute position left and inner link padding accordingly
    if (width > document.body.clientWidth) {
      width = this.state.width + PADDING_LEFT
      left = -8
      padding = 8
    }

    // select component is position fixed
    // add top and left from select component
    top = top + this.state.top
    left = left + this.state.left

    // Checks that the attempted overlay position will fit within the viewport.
    // If it will not fit, tries to adjust the position 'top' so the panel can open fully on-screen.
    // If the select panel is very bottom, tries to adjust the position 'top' so the panel can open fully on-screen.
    // If it still won't fit, sets the offset back to 0 to allow the fallback position to take over.
    const innerHeight = window.innerHeight
    const listHeight = LIST_ITEM_HEIGHT * Math.min(MAX_LIST_LENGTH, options.length) + PADDING_TOP
    if (top < 0) {
      top = 0
    } else if (top + listHeight > innerHeight) {
      top = Math.max(0, innerHeight - listHeight)
    }
    const style = {top, width, left}

    return (

 { this.ref = c }}
        className='mdc-Select-list'
        style={style}
      >
        {options.map((item, i) =>
          <li key={i}
            tabIndex='0'
            className='mdc-Select-listItem'
            data-id={i}
            onClick={this.onClick}
            style={{padding: `0 ${padding}px`}}
            onKeyDown={this.onKeyDown}
            onBlur={this.onBlur}
            ref={elem => { this[`li${i}`] = elem }}
          >
            {item.label}

        )}

    )
  }
}
<commit_msg>select: alignment at the bottom edge (#408)<commit_after>
import React from 'react'
import PropTypes from 'prop-types'
import keycode from 'keycode'
import classnames from 'classnames'

const PADDING_LEFT = 16
const LIST_ITEM_HEIGHT = 48

// list length
const MAX_LIST_LENGTH = 5

export default class Select extends React.Component {
  static propTypes = {
    disabled: PropTypes.bool,
    label: PropTypes.string,
    options: PropTypes.array,
    placeholder: PropTypes.string,
    onChange: PropTypes.func.isRequired,
    name: PropTypes.string
  }

  static defaultProps = {
    options: [
      {value: 'one', label: 'one'},
      {value: 'two', label: 'two'},
      {value: 'three', label: 'three'}
    ],
    placeholder: 'Placeholder',
    value: ''
  }

  state = {
    open: false
  }

  onKeyDown = event => {
    if (event.which === keycode('enter') || event.which === keycode('space')) {
      event.preventDefault()
      this.open()
      return
    }
    if (event.which === keycode('up') || event.which === keycode('left')) {
      event.preventDefault()
      const {options, value} = this.props
      const i = options.findIndex(option => option.value === value)
      if (i > 0) {
        const prev = options[i - 1]
        return this.props.onChange({
          target: {
            name: this.props.name,
            ...prev
          }
        })
      }
    }
    if (event.which === keycode('down') || event.which === keycode('right')) {
      event.preventDefault()
      const {options, value} = this.props
      const i = options.findIndex(option => option.value === value)
      if (i < options.length - 1) {
        const next = options[i + 1]
        return this.props.onChange({
          target: {
            name: this.props.name,
            ...next
          }
        })
      }
    }
  }

  open = () => {
    if (this.props.disabled) { return }
    this.setState({
      open: true
    })
    document.addEventListener('click', this.close)
  }

  close = () => {
    this.setState({
      open: false
    })
    document.removeEventListener('click', this.close)
  }

  findTableTag = (node) => {
    while (node.parentNode) {
      node = node.parentNode
      if (node.tagName === 'TABLE') {
        return true
      }
    }
    return false
  }

  componentDidMount () {
    const isInsideTable = this.findTableTag(this.refWrapper)
    this.setState({
      isInsideTable
    })
  }

  onChange = (item) => {
    this.props.onChange({
      target: {
        name: this.props.name,
        ...item
      }
    })
  }

  onEnter = item => {
    this.props.onChange({
      target: {
        name: this.props.name,
        ...item
      }
    })
    this.onEscape()
  }

  onEscape = () => {
    this.close()
    this.refInput.focus()
  }

  shouldComponentUpdate (nextProps, nextState) {
    if (this.state.open && nextState.open) {
      return false
    }
    return true
  }

  render () {
    const selectedIndex = this.props.options.findIndex(option => option.value === this.props.value)
    const empty = selectedIndex === -1
    const text = empty ? this.props.placeholder : this.props.options[selectedIndex].label

    return (

 { this.refWrapper = c }}
      >
        <input
          className='mdc-Select-input'
          name={this.props.name}
          value={this.props.value}
          disabled={this.props.disabled}
          onKeyDown={this.onKeyDown}
          ref={elem => { this.refInput = elem }}
          readOnly
        />
        {
          this.props.label && {this.props.label}
        }

            {text}

        {
          this.state.open &&
          <List
            options={this.props.options}
            selectedIndex={selectedIndex}
            onClick={this.onChange}
            onEnter={this.onEnter}
            refWrapper={this.refWrapper}
            isInsideTable={this.state.isInsideTable}
            onEscape={this.onEscape}
          />
        }

    )
  }
}

export class List extends React.Component {
  static propTypes = {
    options: PropTypes.array.isRequired,
    isInsideTable: PropTypes.bool,
    selectedIndex: PropTypes.number.isRequired,
    onClick: PropTypes.func.isRequired,
    refWrapper: PropTypes.object.isRequired
  }

  state = {
    left: this.props.refWrapper.getBoundingClientRect().left,
    top: this.props.refWrapper.getBoundingClientRect().top,
    width: this.props.refWrapper.getBoundingClientRect().width
  }

  componentDidMount () {
    const index = this.props.selectedIndex

    // create boolean helper variables
    const scrollable = this.props.options.length > MAX_LIST_LENGTH
    const indexWithinFirstTwoItems = index < 2

    if (scrollable && !indexWithinFirstTwoItems) {
      const scrollTop = (LIST_ITEM_HEIGHT * (index - 2))
      this.ref.scrollTop = scrollTop
    }

    const focus = index >= 0 ? index : 0
    this[`li${focus}`].focus()

    window.addEventListener('resize', this.resize)
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.resize)
  }

  resize = () => {
    const {left, top, width} = this.props.refWrapper.getBoundingClientRect()
    this.setState({
      left,
      top,
      width
    })
  }

  onClick = event => {
    const index = parseInt(event.currentTarget.getAttribute('data-id'))
    this.props.onClick(this.props.options[index])
  }

  onBlur = event => {
    // close list when focus is outside of list
    if (event.relatedTarget && !event.relatedTarget.classList.contains('mdc-Select-listItem')) {
      this.props.onEscape()
    }
  }

  onKeyDown = event => {
    const index = parseInt(event.currentTarget.getAttribute('data-id'))
    if (event.which === keycode('enter')) {
      return this.props.onEnter(this.props.options[index])
    }
    if (event.which === keycode('escape')) {
      return this.props.onEscape()
    }
    if (event.which === keycode('down')) {
      event.preventDefault()
      if (event.target.nextSibling) {
        return event.target.nextSibling.focus()
      }
    }
    if (event.which === keycode('up')) {
      event.preventDefault()
      if (event.target.previousSibling) {
        return event.target.previousSibling.focus()
      }
    }
  }

  render () {
    // CSS space
    let PADDING_TOP = -22
    if (this.props.isInsideTable) {
      // when select component is inside a table cell we have to remove
      // border bottom, padding top and padding bottom.
      // this changes the location of the text.
      // that leads to the list menu / overlay no being directly on top of the text.
      // we therefore have to modify the padding top to fix the overlay position.
      PADDING_TOP = 24
    }

    const {options, selectedIndex} = this.props

    // handle list absolute position top
    const paddingTop = PADDING_TOP

    let top
    if (selectedIndex === -1) {
      // set position to first element, i.e. selectedIndex = 0
      top = -1 * paddingTop
    } else {
      top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * selectedIndex))
    }

    // handle scrollable lists with more than 5 list items
    if (options.length > MAX_LIST_LENGTH) {
      if (selectedIndex >= 2 && selectedIndex <= options.length - 3) {
        // handle "center" items => always set to third position
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 2))
      } else if (selectedIndex === options.length - 2) {
        // handle second last item
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 3))
      } else if (selectedIndex === options.length - 1) {
        // handle last item
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 4))
      }
    }

    let width = this.state.width + (2 * PADDING_LEFT)
    let left = this.props.isInsideTable ? -17 : -16
    let padding = 16

    // check if select overlay is wider than window which would cause horizontal overflow
    // if so decrease padding left and right from 16px to 8px
    // adjust absolute position left and inner link padding accordingly
    if (width > document.body.clientWidth) {
      width = this.state.width + PADDING_LEFT
      left = -8
      padding = 8
    }

    // select component is position fixed
    // add top and left from select component
    top = top + this.state.top
    left = left + this.state.left

    // Checks that the attempted overlay position will fit within the viewport.
    // If it will not fit, tries to adjust the position 'top' so the panel can open fully on-screen.
    // If the select panel is very bottom, tries to adjust the position 'top' so the panel can open fully on-screen.
    // If it still won't fit, sets the offset back to 0 to allow the fallback position to take over.
    const innerHeight = window.innerHeight
    let listHeight = LIST_ITEM_HEIGHT * Math.min(MAX_LIST_LENGTH, options.length)
    if (this.props.isInsideTable) {
      listHeight += PADDING_TOP
    } else {
      listHeight -= PADDING_TOP
    }
    if (top < 0) {
      top = 0
    } else if (top + listHeight > innerHeight) {
      top = Math.max(0, innerHeight - listHeight)
    }
    const style = {top, width, left}

    return (

 { this.ref = c }}
        className='mdc-Select-list'
        style={style}
      >
        {options.map((item, i) =>
          <li key={i}
            tabIndex='0'
            className='mdc-Select-listItem'
            data-id={i}
            onClick={this.onClick}
            style={{padding: `0 ${padding}px`}}
            onKeyDown={this.onKeyDown}
            onBlur={this.onBlur}
            ref={elem => { this[`li${i}`] = elem }}
          >
            {item.label}

        )}

    )
  }
}
<|endoftext|>


<commit_before>/*===============================================================================
************   Smart Select   ************
===============================================================================*/
app.initSmartSelects = function (pageContainer) {
    var page = $(pageContainer);
    if (page.length === 0) return;

    var selects = page.find('.smart-select');
    if (selects.length === 0) return;

    selects.each(function () {
        var smartSelect = $(this);

        var $select = smartSelect.find('select');
        if ($select.length === 0) return;

        var select = $select[0];
        if (select.length === 0) return;

        var valueText = [];
        for (var i = 0; i < select.length; i++) {
            if (select[i].selected) valueText.push(select[i].textContent.trim());
        }

        var itemAfter = smartSelect.find('.item-after');
        if (itemAfter.length === 0) {
            smartSelect.find('.item-inner').append('
' + valueText.join(', ') + '
');
        }
        else {
            var selectedText = itemAfter.text();
            if (itemAfter.hasClass('smart-select-value')) {
                for (i = 0; i < select.length; i++) {
                    select[i].selected = select[i].textContent.trim() === selectedText.trim();
                }
            } else {
                itemAfter.text(valueText);
            }
        }

    });

};
app.smartSelectOpen = function (smartSelect) {
    smartSelect = $(smartSelect);
    if (smartSelect.length === 0) return;

    // Find related view
    var view = smartSelect.parents('.' + app.params.viewClass);
    if (view.length === 0) return;
    view = view[0].f7View;
    if (!view) return;

    // Parameters
    var openIn = smartSelect.attr('data-open-in');
    if (!openIn) openIn = app.params.smartSelectInPopup ? 'popup' : 'page';

    var pageTitle = smartSelect.attr('data-page-title') || smartSelect.find('.item-title').text();
    var backText = smartSelect.attr('data-back-text') || app.params.smartSelectBackText;
    var closeText = smartSelect.attr('data-popup-close-text') || smartSelect.attr('data-back-text') || app.params.smartSelectPopupCloseText ;
    var backOnSelect = smartSelect.attr('data-back-onselect') ? (smartSelect.attr('data-back-onselect') === 'true' ? true : false) : app.params.smartSelectBackOnSelect;
    var formTheme = smartSelect.attr('data-form-theme') || app.params.smartSelectFormTheme;
    var navbarTheme = smartSelect.attr('data-navbar-theme') || app.params.smartSelectNavbarTheme;
    var virtualList = smartSelect.attr('data-virtual-list') === 'true';
    var virtualListItemHeight = smartSelect.attr('data-virtual-list-height');

    // Collect all options/values
    var select = smartSelect.find('select')[0];
    var $select = $(select);
    if (select.disabled || smartSelect.hasClass('disabled') || $select.hasClass('disabled')) {
        return;
    }
    var values = [];
    var id = (new Date()).getTime();
    var inputType = select.multiple ? 'checkbox' : 'radio';
    var inputName = inputType + '-' + id;
    var option, optionHasMedia, optionImage, optionIcon, optionGroup, optionGroupLabel, optionPreviousGroup, optionShowGroupLabel, previousGroup;
    for (var i = 0; i < select.length; i++) {
        option = $(select[i]);
        if (option[0].disabled) continue;
        optionImage = option.attr('data-option-image') || $select.attr('data-option-image');
        optionIcon = option.attr('data-option-icon') || $select.attr('data-option-icon');
        optionHasMedia = optionImage || optionIcon || inputType === 'checkbox';
        optionGroup = option.parent('optgroup')[0];
        optionGroupLabel = optionGroup && optionGroup.label;
        optionShowGroupLabel = false;
        if (optionGroup) {
            if (optionGroup !== previousGroup) {
                optionShowGroupLabel = true;
                previousGroup = optionGroup;
            }
        }
        values.push({
            value: option[0].value,
            text: option[0].textContent.trim(),
            selected: option[0].selected,
            group: optionGroup,
            groupLabel: optionGroupLabel,
            showGroupLabel: optionShowGroupLabel,
            image: optionImage,
            icon: optionIcon,
            disabled: option[0].disabled,
            inputType: inputType,
            id: id,
            hasMedia: optionHasMedia,
            checkbox: inputType === 'checkbox',
            inputName: inputName,
            test: this
        });
    }

    // Item template/HTML
    if (!app._compiledTemplates.smartSelectItem) {
        app._compiledTemplates.smartSelectItem = t7.compile(app.params.smartSelectItemTemplate ||
            '{{#if showGroupLabel}}' +
            '
{{groupLabel}}
' +
            '{{/if}}' +
            '
' +
                '' +
                    '<input type="{{inputType}}" name="{{inputName}}" value="{{value}}" {{#if selected}}checked{{/if}}>' +
                    '{{#if hasMedia}}' +
                    '
' +
                        '{{#if checkbox}}{{/if}}' +
                        '{{#if icon}}{{/if}}' +
                        '{{#if image}}{{/if}}' +
                    '
' +
                    '{{/if}}' +
                    '
' +
                        '
{{text}}
' +
                    '
' +
                '' +
            '
'
        );
    }
    var smartSelectItemTemplate = app._compiledTemplates.smartSelectItem;

    var inputsHTML = '';
    if (!virtualList) {
        for (var j = 0; j < values.length; j++) {
            inputsHTML += smartSelectItemTemplate(values[j]);
        }
    }

    // Navbar HTML
    if (!app._compiledTemplates.smartSelectNavbar) {
        app._compiledTemplates.smartSelectNavbar = t7.compile(app.params.smartSelectNavbarTemplate ||
            '
' +
                '
' +
                    '{{leftTemplate}}' +
                    '
{{pageTitle}}
' +
                '
' +
            '
'
        );
    }
    var navbarHTML = app._compiledTemplates.smartSelectNavbar({
        pageTitle: pageTitle,
        backText: backText,
        closeText: closeText,
        openIn: openIn,
        navbarTheme: navbarTheme,
        inPopup: openIn === 'popup',
        inPage: openIn === 'page',
        leftTemplate: openIn === 'popup' ? app.params.smartSelectPopupCloseTemplate.replace(/{{closeText}}/g, closeText) : app.params.smartSelectBackTemplate.replace(/{{backText}}/g, backText)
    });

    // Determine navbar layout type - static/fixed/through
    var noNavbar = '', noToolbar = '', navbarLayout;
    if (openIn === 'page') {
        navbarLayout = 'static';
        if (smartSelect.parents('.navbar-through').length > 0) navbarLayout = 'through';
        if (smartSelect.parents('.navbar-fixed').length > 0) navbarLayout = 'fixed';
        noToolbar = smartSelect.parents('.page').hasClass('no-toolbar') ? 'no-toolbar' : '';
        noNavbar  = smartSelect.parents('.page').hasClass('no-navbar')  ? 'no-navbar'  : 'navbar-' + navbarLayout;
    }
    else {
        navbarLayout = 'fixed';
    }

    // Page Layout
    var pageName = 'smart-select-' + inputName;

    var useSearchbar = typeof smartSelect.data('searchbar') === 'undefined' ? app.params.smartSelectSearchbar : (smartSelect.data('searchbar') === 'true' ? true : false);
    var searchbarPlaceholder, searchbarCancel;

    if (useSearchbar) {
        searchbarPlaceholder = smartSelect.data('searchbar-placeholder') || 'Search';
        searchbarCancel = smartSelect.data('searchbar-cancel') || 'Cancel';
    }

    var searchbarHTML =   '<form class="searchbar" data-search-list=".smart-select-list-' + id + '" data-search-in=".item-title">' +
                            '
' +
                                '<input type="search" placeholder="' + searchbarPlaceholder + '">' +
                                '' +
                            '
' +
                            '' + searchbarCancel + '' +
                          '</form>' +
                          '

';

    var pageHTML =
        (navbarLayout === 'through' ? navbarHTML : '') +
        '
' +
        '
' +
             (navbarLayout === 'fixed' ? navbarHTML : '') +
             (useSearchbar ? searchbarHTML : '') +
        '
' +
               (navbarLayout === 'static' ? navbarHTML : '') +
        '
' +
        '
' +
                    (virtualList ? '' : inputsHTML) +
        '
' +
        '
' +
        '
' +
        '
' +
        '
';

    // Define popup
    var popup;

    // Event Listeners on new page
    function handleInputs(container) {
        if (virtualList) {
            var virtualListInstance = app.virtualList($(container).find('.virtual-list'), {
                items: values,
                template: smartSelectItemTemplate,
                height: virtualListItemHeight || undefined,
                searchByItem: function (query, index, item) {
                    if (item.text.toLowerCase().indexOf(query.trim()) >=0 ) return true;
                    return false;
                }
            });
            $(container).once(openIn === 'popup' ? 'closed': 'pageBeforeRemove', function () {
                if (virtualListInstance && virtualListInstance.destroy) virtualListInstance.destroy();
            });
        }
        $(container).on('change', 'input[name="' + inputName + '"]', function () {
            var input = this;
            var value = input.value;
            var optionText = [];
            if (input.type === 'checkbox') {
                var values = [];
                for (var i = 0; i < select.options.length; i++) {
                    var option = select.options[i];
                    if (option.value === value) {
                        option.selected = input.checked;
                    }
                    if (option.selected) {
                        optionText.push(option.textContent.trim());
                    }
                }
            }
            else {
                optionText = [smartSelect.find('option[value="' + value + '"]').text()];
                select.value = value;
            }

            $select.trigger('change');
            smartSelect.find('.item-after').text(optionText.join(', '));
            if (backOnSelect && inputType === 'radio') {
                if (openIn === 'popup') app.closeModal(popup);
                else view.router.back();
            }
        });
    }
    function pageInit(e) {
        var page = e.detail.page;
        if (page.name === pageName) {
            $(document).off('pageInit', pageInit);
            handleInputs(page.container);
        }
    }

    // Load content
    if (openIn === 'popup') {
        popup = app.popup(
                '
' +
                    '
' +
                        pageHTML +
                    '
' +
                '
'
                );
        app.initPage($(popup).find('.page'));
        handleInputs(popup);
    }
    else {
        $(document).on('pageInit', pageInit);
        view.router.load({content: pageHTML});
    }
};
<commit_msg>Space between values<commit_after>/*===============================================================================
************   Smart Select   ************
===============================================================================*/
app.initSmartSelects = function (pageContainer) {
    var page = $(pageContainer);
    if (page.length === 0) return;

    var selects = page.find('.smart-select');
    if (selects.length === 0) return;

    selects.each(function () {
        var smartSelect = $(this);

        var $select = smartSelect.find('select');
        if ($select.length === 0) return;

        var select = $select[0];
        if (select.length === 0) return;

        var valueText = [];
        for (var i = 0; i < select.length; i++) {
            if (select[i].selected) valueText.push(select[i].textContent.trim());
        }

        var itemAfter = smartSelect.find('.item-after');
        if (itemAfter.length === 0) {
            smartSelect.find('.item-inner').append('
' + valueText.join(', ') + '
');
        }
        else {
            var selectedText = itemAfter.text();
            if (itemAfter.hasClass('smart-select-value')) {
                for (i = 0; i < select.length; i++) {
                    select[i].selected = select[i].textContent.trim() === selectedText.trim();
                }
            } else {
                itemAfter.text(valueText.join(', '));
            }
        }

    });

};
app.smartSelectOpen = function (smartSelect) {
    smartSelect = $(smartSelect);
    if (smartSelect.length === 0) return;

    // Find related view
    var view = smartSelect.parents('.' + app.params.viewClass);
    if (view.length === 0) return;
    view = view[0].f7View;
    if (!view) return;

    // Parameters
    var openIn = smartSelect.attr('data-open-in');
    if (!openIn) openIn = app.params.smartSelectInPopup ? 'popup' : 'page';

    var pageTitle = smartSelect.attr('data-page-title') || smartSelect.find('.item-title').text();
    var backText = smartSelect.attr('data-back-text') || app.params.smartSelectBackText;
    var closeText = smartSelect.attr('data-popup-close-text') || smartSelect.attr('data-back-text') || app.params.smartSelectPopupCloseText ;
    var backOnSelect = smartSelect.attr('data-back-onselect') ? (smartSelect.attr('data-back-onselect') === 'true' ? true : false) : app.params.smartSelectBackOnSelect;
    var formTheme = smartSelect.attr('data-form-theme') || app.params.smartSelectFormTheme;
    var navbarTheme = smartSelect.attr('data-navbar-theme') || app.params.smartSelectNavbarTheme;
    var virtualList = smartSelect.attr('data-virtual-list') === 'true';
    var virtualListItemHeight = smartSelect.attr('data-virtual-list-height');

    // Collect all options/values
    var select = smartSelect.find('select')[0];
    var $select = $(select);
    if (select.disabled || smartSelect.hasClass('disabled') || $select.hasClass('disabled')) {
        return;
    }
    var values = [];
    var id = (new Date()).getTime();
    var inputType = select.multiple ? 'checkbox' : 'radio';
    var inputName = inputType + '-' + id;
    var option, optionHasMedia, optionImage, optionIcon, optionGroup, optionGroupLabel, optionPreviousGroup, optionShowGroupLabel, previousGroup;
    for (var i = 0; i < select.length; i++) {
        option = $(select[i]);
        if (option[0].disabled) continue;
        optionImage = option.attr('data-option-image') || $select.attr('data-option-image');
        optionIcon = option.attr('data-option-icon') || $select.attr('data-option-icon');
        optionHasMedia = optionImage || optionIcon || inputType === 'checkbox';
        optionGroup = option.parent('optgroup')[0];
        optionGroupLabel = optionGroup && optionGroup.label;
        optionShowGroupLabel = false;
        if (optionGroup) {
            if (optionGroup !== previousGroup) {
                optionShowGroupLabel = true;
                previousGroup = optionGroup;
            }
        }
        values.push({
            value: option[0].value,
            text: option[0].textContent.trim(),
            selected: option[0].selected,
            group: optionGroup,
            groupLabel: optionGroupLabel,
            showGroupLabel: optionShowGroupLabel,
            image: optionImage,
            icon: optionIcon,
            disabled: option[0].disabled,
            inputType: inputType,
            id: id,
            hasMedia: optionHasMedia,
            checkbox: inputType === 'checkbox',
            inputName: inputName,
            test: this
        });
    }

    // Item template/HTML
    if (!app._compiledTemplates.smartSelectItem) {
        app._compiledTemplates.smartSelectItem = t7.compile(app.params.smartSelectItemTemplate ||
            '{{#if showGroupLabel}}' +
            '
{{groupLabel}}
' +
            '{{/if}}' +
            '
' +
                '' +
                    '<input type="{{inputType}}" name="{{inputName}}" value="{{value}}" {{#if selected}}checked{{/if}}>' +
                    '{{#if hasMedia}}' +
                    '
' +
                        '{{#if checkbox}}{{/if}}' +
                        '{{#if icon}}{{/if}}' +
                        '{{#if image}}{{/if}}' +
                    '
' +
                    '{{/if}}' +
                    '
' +
                        '
{{text}}
' +
                    '
' +
                '' +
            '
'
        );
    }
    var smartSelectItemTemplate = app._compiledTemplates.smartSelectItem;

    var inputsHTML = '';
    if (!virtualList) {
        for (var j = 0; j < values.length; j++) {
            inputsHTML += smartSelectItemTemplate(values[j]);
        }
    }

    // Navbar HTML
    if (!app._compiledTemplates.smartSelectNavbar) {
        app._compiledTemplates.smartSelectNavbar = t7.compile(app.params.smartSelectNavbarTemplate ||
            '
' +
                '
' +
                    '{{leftTemplate}}' +
                    '
{{pageTitle}}
' +
                '
' +
            '
'
        );
    }
    var navbarHTML = app._compiledTemplates.smartSelectNavbar({
        pageTitle: pageTitle,
        backText: backText,
        closeText: closeText,
        openIn: openIn,
        navbarTheme: navbarTheme,
        inPopup: openIn === 'popup',
        inPage: openIn === 'page',
        leftTemplate: openIn === 'popup' ? app.params.smartSelectPopupCloseTemplate.replace(/{{closeText}}/g, closeText) : app.params.smartSelectBackTemplate.replace(/{{backText}}/g, backText)
    });

    // Determine navbar layout type - static/fixed/through
    var noNavbar = '', noToolbar = '', navbarLayout;
    if (openIn === 'page') {
        navbarLayout = 'static';
        if (smartSelect.parents('.navbar-through').length > 0) navbarLayout = 'through';
        if (smartSelect.parents('.navbar-fixed').length > 0) navbarLayout = 'fixed';
        noToolbar = smartSelect.parents('.page').hasClass('no-toolbar') ? 'no-toolbar' : '';
        noNavbar  = smartSelect.parents('.page').hasClass('no-navbar')  ? 'no-navbar'  : 'navbar-' + navbarLayout;
    }
    else {
        navbarLayout = 'fixed';
    }

    // Page Layout
    var pageName = 'smart-select-' + inputName;

    var useSearchbar = typeof smartSelect.data('searchbar') === 'undefined' ? app.params.smartSelectSearchbar : (smartSelect.data('searchbar') === 'true' ? true : false);
    var searchbarPlaceholder, searchbarCancel;

    if (useSearchbar) {
        searchbarPlaceholder = smartSelect.data('searchbar-placeholder') || 'Search';
        searchbarCancel = smartSelect.data('searchbar-cancel') || 'Cancel';
    }

    var searchbarHTML =   '<form class="searchbar" data-search-list=".smart-select-list-' + id + '" data-search-in=".item-title">' +
                            '
' +
                                '<input type="search" placeholder="' + searchbarPlaceholder + '">' +
                                '' +
                            '
' +
                            '' + searchbarCancel + '' +
                          '</form>' +
                          '

';

    var pageHTML =
        (navbarLayout === 'through' ? navbarHTML : '') +
        '
' +
        '
' +
             (navbarLayout === 'fixed' ? navbarHTML : '') +
             (useSearchbar ? searchbarHTML : '') +
        '
' +
               (navbarLayout === 'static' ? navbarHTML : '') +
        '
' +
        '
' +
                    (virtualList ? '' : inputsHTML) +
        '
' +
        '
' +
        '
' +
        '
' +
        '
';

    // Define popup
    var popup;

    // Event Listeners on new page
    function handleInputs(container) {
        if (virtualList) {
            var virtualListInstance = app.virtualList($(container).find('.virtual-list'), {
                items: values,
                template: smartSelectItemTemplate,
                height: virtualListItemHeight || undefined,
                searchByItem: function (query, index, item) {
                    if (item.text.toLowerCase().indexOf(query.trim()) >=0 ) return true;
                    return false;
                }
            });
            $(container).once(openIn === 'popup' ? 'closed': 'pageBeforeRemove', function () {
                if (virtualListInstance && virtualListInstance.destroy) virtualListInstance.destroy();
            });
        }
        $(container).on('change', 'input[name="' + inputName + '"]', function () {
            var input = this;
            var value = input.value;
            var optionText = [];
            if (input.type === 'checkbox') {
                var values = [];
                for (var i = 0; i < select.options.length; i++) {
                    var option = select.options[i];
                    if (option.value === value) {
                        option.selected = input.checked;
                    }
                    if (option.selected) {
                        optionText.push(option.textContent.trim());
                    }
                }
            }
            else {
                optionText = [smartSelect.find('option[value="' + value + '"]').text()];
                select.value = value;
            }

            $select.trigger('change');
            smartSelect.find('.item-after').text(optionText.join(', '));
            if (backOnSelect && inputType === 'radio') {
                if (openIn === 'popup') app.closeModal(popup);
                else view.router.back();
            }
        });
    }
    function pageInit(e) {
        var page = e.detail.page;
        if (page.name === pageName) {
            $(document).off('pageInit', pageInit);
            handleInputs(page.container);
        }
    }

    // Load content
    if (openIn === 'popup') {
        popup = app.popup(
                '
' +
                    '
' +
                        pageHTML +
                    '
' +
                '
'
                );
        app.initPage($(popup).find('.page'));
        handleInputs(popup);
    }
    else {
        $(document).on('pageInit', pageInit);
        view.router.load({content: pageHTML});
    }
};
<|endoftext|>


<commit_before>function note(name, octave) {
  const notes = {
    C: 16.35,
    Cs: 17.32,
    D: 18.35,
    Ds: 19.45,
    E: 20.60,
    F: 21.83,
    Fs: 23.12,
    G: 24.50,
    Gs: 25.96,
    A: 27.50,
    Bb: 29.14,
    B: 30.87,
  };
  if (notes[name]) {
    return notes[name] * (2 ** octave);
  }
  return 0;
}

const noteNames = ['C', 'Cs', 'D', 'Ds', 'E', 'F', 'Fs', 'G', 'Gs', 'A', 'Bb', 'B'];

function scaleFromPattern(pattern, root = 'C', initialOctave = 3, numberOfOctaves = 3) {
  let i = 0;
  const scale = [];
  const initialIndex = noteNames.indexOf(root);

  for (i; i <= numberOfOctaves * 12; i += pattern[(scale.length - 1) % pattern.length]) {
    const noteName = noteNames[(i + initialIndex) % 12];
    const octave = initialOctave + Math.floor((i + initialIndex) / 12);
    scale.push(note(noteName, octave));
  }
  return scale;
}

function scales(scaleName, root = 'C', initialOctave = 3, numberOfOctaves = 3) {
  switch (scaleName) {
    case 'whole':
      return scaleFromPattern([2], root, initialOctave, numberOfOctaves);
    case 'chromatic':
      return scaleFromPattern([1], root, initialOctave, numberOfOctaves);
    case 'major':
      return scaleFromPattern([2, 2, 1, 2, 2, 2, 1], root, initialOctave, numberOfOctaves);
    case 'minor':
      return scaleFromPattern([2, 1, 2, 2, 1, 2, 2], root, initialOctave, numberOfOctaves);
    case 'lydian':
      return scaleFromPattern([2, 2, 2, 1, 2, 2, 1], root, initialOctave, numberOfOctaves);
    case 'mixolydian':
      return scaleFromPattern([2, 2, 1, 2, 2, 1, 2], root, initialOctave, numberOfOctaves);
    case 'pentatonic':
      return scaleFromPattern([2, 2, 3, 2, 4], root, initialOctave, numberOfOctaves);
    case 'octatonic':
      return scaleFromPattern([1, 2], root, initialOctave, numberOfOctaves);
    default: // return pentatonic if no scale found
      return scaleFromPattern([2, 2, 3, 2, 4], root, initialOctave, numberOfOctaves);
  }
}

export default scales;
<commit_msg>Increase precision of note frequencies<commit_after>function note(name, octave) {
  const notes = {
    C: 16.351,
    Cs: 17.324,
    D: 18.354,
    Ds: 19.445,
    E: 20.601,
    F: 21.827,
    Fs: 23.124,
    G: 24.499,
    Gs: 25.956,
    A: 27.50,
    Bb: 29.135,
    B: 30.868,
  };
  if (notes[name]) {
    return notes[name] * (2 ** octave);
  }
  return 0;
}

const noteNames = ['C', 'Cs', 'D', 'Ds', 'E', 'F', 'Fs', 'G', 'Gs', 'A', 'Bb', 'B'];

function scaleFromPattern(pattern, root = 'C', initialOctave = 3, numberOfOctaves = 3) {
  let i = 0;
  const scale = [];
  const initialIndex = noteNames.indexOf(root);

  for (i; i <= numberOfOctaves * 12; i += pattern[(scale.length - 1) % pattern.length]) {
    const noteName = noteNames[(i + initialIndex) % 12];
    const octave = initialOctave + Math.floor((i + initialIndex) / 12);
    scale.push(note(noteName, octave));
  }
  return scale;
}

function scales(scaleName, root = 'C', initialOctave = 3, numberOfOctaves = 3) {
  switch (scaleName) {
    case 'whole':
      return scaleFromPattern([2], root, initialOctave, numberOfOctaves);
    case 'chromatic':
      return scaleFromPattern([1], root, initialOctave, numberOfOctaves);
    case 'major':
      return scaleFromPattern([2, 2, 1, 2, 2, 2, 1], root, initialOctave, numberOfOctaves);
    case 'minor':
      return scaleFromPattern([2, 1, 2, 2, 1, 2, 2], root, initialOctave, numberOfOctaves);
    case 'lydian':
      return scaleFromPattern([2, 2, 2, 1, 2, 2, 1], root, initialOctave, numberOfOctaves);
    case 'mixolydian':
      return scaleFromPattern([2, 2, 1, 2, 2, 1, 2], root, initialOctave, numberOfOctaves);
    case 'pentatonic':
      return scaleFromPattern([2, 2, 3, 2, 4], root, initialOctave, numberOfOctaves);
    case 'octatonic':
      return scaleFromPattern([1, 2], root, initialOctave, numberOfOctaves);
    default: // return pentatonic if no scale found
      return scaleFromPattern([2, 2, 3, 2, 4], root, initialOctave, numberOfOctaves);
  }
}

export default scales;
<|endoftext|>


<commit_before>
// require the redis driver
XT.redis = require('redis');

/** @namespace
  The central caching mechanism that allows for seamless integration
  with a redis store.
*/
try {
  XT.cache = XT.redis.createClient(
    XT.opts['redis-port'],
    XT.opts['redis-host']
  ); // NEEDS TO USE GLOBAL PROPERTIES
} catch(err) {
  issue(XT.fatal("Could not connect to Redis server"));
}

// set up some basic error handling
// should probably be FAR more elaborate in the future
XT.cache.on('error', function(e) { issue(XT.warn(e)); });

process.once('xtBootstrapping', function() {
  XT.log("Cache looking at host %@ on port %@".f(XT.opts['redis-host'], XT.opts['redis-port']));
})
<commit_msg>allow the options to use a non-default value in the load process<commit_after>
// require the redis driver
XT.redis = require('redis');

process.once('xtBootstrapping', function() {

  /** @namespace
    The central caching mechanism that allows for seamless integration
    with a redis store.
  */
  try {
    XT.cache = XT.redis.createClient(
      XT.opts['redis-port'],
      XT.opts['redis-host']
    ); // NEEDS TO USE GLOBAL PROPERTIES
  } catch(err) {
    issue(XT.fatal("Could not connect to Redis server"));
  }

  // set up some basic error handling
  // should probably be FAR more elaborate in the future
  XT.cache.on('error', function(e) { issue(XT.warn(e)); });

  XT.log("Cache looking at host %@ on port %@".f(XT.opts['redis-host'], XT.opts['redis-port']));
})
<|endoftext|>


<commit_before>import curry2 from "./internal/curry2";
import _slice from "./internal/slice";
import checkForMethod from "./internal/check_for_method";

/**
 * Returns a new list containing all but the first `n` elements of the given `list`.
 *
 * @static
 * @memberOf R
 * @category List
 * @param {number} n The number of elements of `list` to skip.
 * @param {Array} list The array to consider.
 * @return {Array} The last `n` elements of `list`.
 * @alias drop
 */
var skip = curry2(checkForMethod('skip', function _skip(n, list) {
    return _slice(list, n);
}));

export default skip;
<commit_msg>Fix skip test failure<commit_after>import curry2 from "./internal/curry2";
import _slice from "./internal/slice";
import checkForMethod from "./internal/check_for_method";

/**
 * Returns a new list containing all but the first `n` elements of the given `list`.
 *
 * @static
 * @memberOf R
 * @category List
 * @param {number} n The number of elements of `list` to skip.
 * @param {Array} list The array to consider.
 * @return {Array} The last `n` elements of `list`.
 * @alias drop
 */
var skip = curry2(checkForMethod('skip', function _skip(n, list) {
    if (n < list.length) {
      return _slice(list, n);
    } else {
      return [];
    }
}));

export default skip;
<|endoftext|>


<commit_before>function getExternalAssets(mode) {
	switch (mode) {
	case "dev":
	case "watch": {
		return `

		<link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
		<link href="prismjs/themes/prism.css" rel="stylesheet">`;
	}
	default:
		return `

		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
		<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.css" rel="stylesheet">
		`;
	}
}

function getDevServerJs(mode) {
	if (mode === "watch") {
		return '';
	}
	return "";
}

function getIndexContent() {
	return `

							View project on
 GitHub

					Documentation
					Demo

Click on the chart, zoom with scroll, pan with drag

MIT license

 `;
}

function getDocumentationContent() {
	return `.

`;
}

module.exports = function(params) {
	const { mode, page } = params.htmlWebpackPlugin.options;

	const { chunks } = params.htmlWebpackPlugin.files;

	return `<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
		<meta name="description" content="Highly customizable stock charts">
		<meta name="author" content="rrag">

		<link href="data:image/x-icon;base64,AAABAAEAEBAAAAAAAABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAAAAAAAACAAIAACQAAAoODgAEAAQAAiQCAAwWCgAEJAQADggIAAQSHgAODhAAAA4AAAwIBAAmJCgAABQIACQkJAAmJCYAKCQoAAAcAAAEHAQABhwGAAgcCAAmJCQAACoAAAQGBAAGBgYAFgIAAAAMCAAKKgoABAYCAAA4AAAEFAQAAjgCAAQ4BAAAAhoAHAICABQUFAAAIgAACgwMAAwGBAAEDAQADg4AAA4GBgAGDAYADDAMACQiJAAmIiYAABoAAAoMCAAAPgAABBoEAAg+CAAABAAAAgQCAAAoAAAACggACigKAAwoDAAEBAIAABIAAAA2AAAKKAgAAAAaAAYgCAAaAAAAAA4cAAogDAASEhIABgoKACgoKAAAIAAAChIIAAQgBAAAAggAAgIKABISEAAENgAAAiAAAAAuAAAMBAQABAoEAAAQCAAKCgoAABgAAAoKCAACGAIAADwAAAIGHAAAAgAAAgICAAAmAAAEAgQAAiYCAAoKAgAANAAAChAKACYmJgAGCAoAAB4AAAAACAAADBoAAgAKAAYICAAoJiYACAgKAAgQBAAMAgQAAiwCAAgICAAADggACggKAAA6AgAMAgIABAgCAAIWAgAMEAQAAjoCAAgWCAAMCAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ0VgYGBgYGBgYGBgYGBFQ0UkbGxsbGxsbGxsbGwZJEUPREREREREaGFEREREZgNFZyNAQEBAQCkaQEBAQEAjFmAqT09PaidMXXNqDHNwCGAPJlJSUlJCbz8cbl84aApFYDUAAFgAPE5eJQA7HjRZDy5IclpiU2tIIV4BLzw2FBAuBTN0AjF1XzkgFVxGXiwRLgdWYgtGNAAAYhc2U1pVLS4TBRgEE1BbWzIfMihiK2AuTWlUVDBUVFQwRz12EgZFDQkiPj4+Ij4+Pj5kPkFXEGBlY2NJNw5RGxttY2NjSmBFSzo6OnEdcXFxcTo6OktFQ0VgYGBgYBAQEBBgYGBFQwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" rel="icon" type="image/x-icon" />
		<title>React Stockcharts - Home</title>
		${getExternalAssets(mode)}

		${page === "index" ? `` : ""}

		${page === "index" ? getIndexContent() : getDocumentationContent()}

		${page === "index"
			? `<script type="text/javascript" src="${chunks["react-stockcharts-home"].entry}"></script>`
			: `<script type="text/javascript" src="${chunks["react-stockcharts-documentation"].entry}"></script>`}

		${getDevServerJs(mode)}

`;

};<commit_msg>fix cdn path<commit_after>function getExternalAssets(mode) {
	switch (mode) {
	case "dev":
	case "watch": {
		return `

		<link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
		<link href="prismjs/themes/prism.css" rel="stylesheet">`;
	}
	default:
		return `

		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
		<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.css" rel="stylesheet">
		`;
	}
}

function getDevServerJs(mode) {
	if (mode === "watch") {
		return '';
	}
	return "";
}

function getIndexContent() {
	return `

							View project on
 GitHub

					Documentation
					Demo

Click on the chart, zoom with scroll, pan with drag

MIT license

 `;
}

function getDocumentationContent() {
	return `.

`;
}

module.exports = function(params) {
	const { mode, page } = params.htmlWebpackPlugin.options;

	const { chunks } = params.htmlWebpackPlugin.files;

	return `<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
		<meta name="description" content="Highly customizable stock charts">
		<meta name="author" content="rrag">

		<link href="data:image/x-icon;base64,AAABAAEAEBAAAAAAAABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAAAAAAAACAAIAACQAAAoODgAEAAQAAiQCAAwWCgAEJAQADggIAAQSHgAODhAAAA4AAAwIBAAmJCgAABQIACQkJAAmJCYAKCQoAAAcAAAEHAQABhwGAAgcCAAmJCQAACoAAAQGBAAGBgYAFgIAAAAMCAAKKgoABAYCAAA4AAAEFAQAAjgCAAQ4BAAAAhoAHAICABQUFAAAIgAACgwMAAwGBAAEDAQADg4AAA4GBgAGDAYADDAMACQiJAAmIiYAABoAAAoMCAAAPgAABBoEAAg+CAAABAAAAgQCAAAoAAAACggACigKAAwoDAAEBAIAABIAAAA2AAAKKAgAAAAaAAYgCAAaAAAAAA4cAAogDAASEhIABgoKACgoKAAAIAAAChIIAAQgBAAAAggAAgIKABISEAAENgAAAiAAAAAuAAAMBAQABAoEAAAQCAAKCgoAABgAAAoKCAACGAIAADwAAAIGHAAAAgAAAgICAAAmAAAEAgQAAiYCAAoKAgAANAAAChAKACYmJgAGCAoAAB4AAAAACAAADBoAAgAKAAYICAAoJiYACAgKAAgQBAAMAgQAAiwCAAgICAAADggACggKAAA6AgAMAgIABAgCAAIWAgAMEAQAAjoCAAgWCAAMCAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ0VgYGBgYGBgYGBgYGBFQ0UkbGxsbGxsbGxsbGwZJEUPREREREREaGFEREREZgNFZyNAQEBAQCkaQEBAQEAjFmAqT09PaidMXXNqDHNwCGAPJlJSUlJCbz8cbl84aApFYDUAAFgAPE5eJQA7HjRZDy5IclpiU2tIIV4BLzw2FBAuBTN0AjF1XzkgFVxGXiwRLgdWYgtGNAAAYhc2U1pVLS4TBRgEE1BbWzIfMihiK2AuTWlUVDBUVFQwRz12EgZFDQkiPj4+Ij4+Pj5kPkFXEGBlY2NJNw5RGxttY2NjSmBFSzo6OnEdcXFxcTo6OktFQ0VgYGBgYBAQEBBgYGBFQwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" rel="icon" type="image/x-icon" />
		<title>React Stockcharts - Home</title>
		${getExternalAssets(mode)}

		${page === "index" ? `` : ""}

		${page === "index" ? getIndexContent() : getDocumentationContent()}

		${page === "index"
			? `<script type="text/javascript" src="${chunks["react-stockcharts-home"].entry}"></script>`
			: `<script type="text/javascript" src="${chunks["react-stockcharts-documentation"].entry}"></script>`}

		${getDevServerJs(mode)}

`;

};<|endoftext|>


<commit_before>// Copyright 2013-2018, University of Colorado Boulder

/**
 * This toggle button uses a boolean property and a trueNode and falseNode to display its content.
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanToggleNode = require( 'SUN/BooleanToggleNode' );
  var inherit = require( 'PHET_CORE/inherit' );
  var RectangularToggleButton = require( 'SUN/buttons/RectangularToggleButton' );
  var sun = require( 'SUN/sun' );
  var Tandem = require( 'TANDEM/Tandem' );

  /**
   * @param {Node} trueNode
   * @param {Node} falseNode
   * @param booleanProperty
   * @param {Object} [options]
   * @constructor
   */
  function BooleanRectangularToggleButton( trueNode, falseNode, booleanProperty, options ) {

    options = _.extend( { tandem: Tandem.required }, options );

    assert && assert( !options.content, 'options.content cannot be set' );
    options.content = new BooleanToggleNode( trueNode, falseNode, booleanProperty, {
      tandem: options.tandem.createTandem( 'toggleNode' )
    } );

    RectangularToggleButton.call( this, false, true, booleanProperty, options );

    // @private {function} - internally used disposal function
    this.disposeBooleanRectangularToggleButton = function() {
      options.content.dispose();
    };
  }

  sun.register( 'BooleanRectangularToggleButton', BooleanRectangularToggleButton );

  return inherit( RectangularToggleButton, BooleanRectangularToggleButton, {
    /**
     * @public
     */
    dispose: function() {
      this.disposeBooleanRectangularToggleButton();
      RectangularToggleButton.prototype.dispose.call( this );
    }
  } );
} );
<commit_msg>Removed instrumentation from the BooleanRectangularToggleButton.toggleNode, see https://github.com/phetsims/scenery-phet/issues/439<commit_after>// Copyright 2013-2018, University of Colorado Boulder

/**
 * This toggle button uses a boolean property and a trueNode and falseNode to display its content.
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanToggleNode = require( 'SUN/BooleanToggleNode' );
  var inherit = require( 'PHET_CORE/inherit' );
  var RectangularToggleButton = require( 'SUN/buttons/RectangularToggleButton' );
  var sun = require( 'SUN/sun' );
  var Tandem = require( 'TANDEM/Tandem' );

  /**
   * @param {Node} trueNode
   * @param {Node} falseNode
   * @param booleanProperty
   * @param {Object} [options]
   * @constructor
   */
  function BooleanRectangularToggleButton( trueNode, falseNode, booleanProperty, options ) {

    options = _.extend( { tandem: Tandem.required }, options );

    assert && assert( !options.content, 'options.content cannot be set' );
    options.content = new BooleanToggleNode( trueNode, falseNode, booleanProperty );

    RectangularToggleButton.call( this, false, true, booleanProperty, options );

    // @private {function} - internally used disposal function
    this.disposeBooleanRectangularToggleButton = function() {
      options.content.dispose();
    };
  }

  sun.register( 'BooleanRectangularToggleButton', BooleanRectangularToggleButton );

  return inherit( RectangularToggleButton, BooleanRectangularToggleButton, {
    /**
     * @public
     */
    dispose: function() {
      this.disposeBooleanRectangularToggleButton();
      RectangularToggleButton.prototype.dispose.call( this );
    }
  } );
} );
<|endoftext|>


<commit_before>'use strict';

var concat = function (array, ...items) {
  items.forEach (x => {
    if (x) {
      if (Array.isArray (x)) {
        concat (array, ...x);
      } else {
        array.push (x);
      }
    }
  });
  return array;
};

var getText = function (obj, what) {
  return obj.props.id;
};

var getStyle = function (obj, ...styles) {
  var theme = obj.theme || {};
  return concat (
    [],
    theme.base,
    obj.props.kind ? theme[obj.props.kind] : null
  );
};

var getState = function (obj, what) {
  return null;
};

var setState = function (obj, ...states) {
  return null;
};

var getValue = function (obj) {
  return null;
};

var setValue = function (obj, value, ...states) {};

module.exports = {
  getState: getState,
  setState: setState,
  getStyle: getStyle,
  getText: getText,
  getValue: getValue,
  setValue: setValue,
};
<commit_msg>Retrieve the text of components via props.<commit_after>'use strict';

var concat = function (array, ...items) {
  items.forEach (x => {
    if (x) {
      if (Array.isArray (x)) {
        concat (array, ...x);
      } else {
        array.push (x);
      }
    }
  });
  return array;
};

var getText = function (obj, what) {
  return obj.props.text || obj.props.id;
};

var getStyle = function (obj, ...styles) {
  var theme = obj.theme || {};
  return concat (
    [],
    theme.base,
    obj.props.kind ? theme[obj.props.kind] : null
  );
};

var getState = function (obj, what) {
  return null;
};

var setState = function (obj, ...states) {
  return null;
};

var getValue = function (obj) {
  return null;
};

var setValue = function (obj, value, ...states) {};

module.exports = {
  getState: getState,
  setState: setState,
  getStyle: getStyle,
  getText: getText,
  getValue: getValue,
  setValue: setValue,
};
<|endoftext|>