<commit_before>
function db() { }

db.open = function() {
    this.DB = openDatabase('TabSense', '1.0', 'TabSense', 5*1024*1024);
    this.DB.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS '+
            'Window(id INTEGER PRIMARY KEY ASC, wid INTEGER, title TEXT)',
            [], db.onSuccess, db.onError);
    });
    this.DB.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS '+
            'Tab(id INTEGER PRIMARY KEY ASC, tid INTEGER, title TEXT, '+
            'url TEXT, faviconurl TEXT, wid INTEGER, parent INTEGER, '+
            'idx INTEGER, depth INTEGER, status TEXT)',
            [], db.onSuccess, db.onError);
    });
}

db.clear = function() {
    this.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Window', [], db.onSuccess, db.onError);
    });
    this.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Tab', [], db.onSuccess, db.onError);
    });
}

db.onError = function(tx, e) {
    console.error('TabSense DB Error : '+e.message);
}

db.onSuccess = function(tx, r) {
    //console.debug(r);
}

db.put = function(obj) {
    if(obj.constructor == db.window) {
        var win = obj;
        this.DB.transaction(function(tx) {
            tx.executeSql('INSERT INTO Window(wid, title) VALUES (?,?)',
                [win.wid, win.title],
                db.onSuccess,
                db.onError);
        });
    } else if(obj.constructor == db.tab) {
        var tab = obj;
        this.DB.transaction(function(tx) {
            tx.executeSql('INSERT INTO Tab(tid, title, url, faviconurl, '+
                'wid, parent, idx, depth) VALUES (?,?,?,?,?,?,?,?)',
                [ tab.tid, tab.title, tab.url, tab.faviconurl, tab.wid,
                    tab.parent, tab.index, tab.depth ],
                onSuccess,
                db.onError);
        });
    } else {
        alert('Invalid object to save');
    }
}

db.window = function(wid, title) {
    this.wid = wid;
    this.title = title;
}

db.window.get = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('SELECT * FROM Window '+condition, [],
            onSuccess, db.onError);
    });
}

db.window.del = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Window '+condition, [],
            onSuccess, db.onError);
    });
}

db.tab = function(tid, title, url, faviconurl, index, wid, parent, depth) {
    this.tid = tid;
    this.title = title;
    this.url = url;
    this.faviconurl = faviconurl;
    this.index = index;
    this.wid = wid;
    this.parent = parent || -1;
    this.depth = depth || 0;
}

db.tab.get = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('SELECT * FROM Tab '+condition, [],
            onSuccess, db.onError);
    });
}

db.tab.del = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Tab '+condition, [],
            onSuccess, db.onError);
    });
}

db.tab.update = function(set, condition, data, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('UPDATE Tab SET '+set+condition, data,
            onSuccess, db.onError);
    });
}
<commit_msg>pass through onSuccess callback<commit_after>
function db() { }

db.open = function() {
    this.DB = openDatabase('TabSense', '1.0', 'TabSense', 5*1024*1024);
    this.DB.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS '+
            'Window(id INTEGER PRIMARY KEY ASC, wid INTEGER, title TEXT)',
            [], db.onSuccess, db.onError);
    });
    this.DB.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS '+
            'Tab(id INTEGER PRIMARY KEY ASC, tid INTEGER, title TEXT, '+
            'url TEXT, faviconurl TEXT, wid INTEGER, parent INTEGER, '+
            'idx INTEGER, depth INTEGER, status TEXT)',
            [], db.onSuccess, db.onError);
    });
}

db.clear = function() {
    this.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Window', [], db.onSuccess, db.onError);
    });
    this.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Tab', [], db.onSuccess, db.onError);
    });
}

db.onError = function(tx, e) {
    console.error('TabSense DB Error : '+e.message);
}

db.onSuccess = function(tx, r) {
    //console.debug(r);
}

db.put = function(obj, successCb) {
    var onSuccess = successCb || db.onSuccess;
    if(obj.constructor == db.window) {
        var win = obj;
        this.DB.transaction(function(tx) {
            tx.executeSql('INSERT INTO Window(wid, title) VALUES (?,?)',
                [win.wid, win.title],
                onSuccess,
                db.onError);
        });
    } else if(obj.constructor == db.tab) {
        var tab = obj;
        this.DB.transaction(function(tx) {
            tx.executeSql('INSERT INTO Tab(tid, title, url, faviconurl, '+
                'wid, parent, idx, depth) VALUES (?,?,?,?,?,?,?,?)',
                [ tab.tid, tab.title, tab.url, tab.faviconurl, tab.wid,
                    tab.parent, tab.index, tab.depth ],
                onSuccess,
                db.onError);
        });
    } else {
        alert('Invalid object to save');
    }
}

db.window = function(wid, title) {
    this.wid = wid;
    this.title = title;
}

db.window.get = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('SELECT * FROM Window '+condition, [],
            onSuccess, db.onError);
    });
}

db.window.del = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Window '+condition, [],
            onSuccess, db.onError);
    });
}

db.tab = function(tid, title, url, faviconurl, index, wid, parent, depth) {
    this.tid = tid;
    this.title = title;
    this.url = url;
    this.faviconurl = faviconurl;
    this.index = index;
    this.wid = wid;
    this.parent = parent || -1;
    this.depth = depth || 0;
}

db.tab.get = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('SELECT * FROM Tab '+condition, [],
            onSuccess, db.onError);
    });
}

db.tab.del = function(condition, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('DELETE FROM Tab '+condition, [],
            onSuccess, db.onError);
    });
}

db.tab.update = function(set, condition, data, onSuccess) {
    db.DB.transaction(function(tx) {
        tx.executeSql('UPDATE Tab SET '+set+condition, data,
            onSuccess, db.onError);
    });
}
<|endoftext|>


<commit_before>/**
 * Created by Manuel on 22/07/16.
 */

import {Model}      from "../../core/Model";
import {DataSource} from "../DataSource.js";

export class LocalModel extends Model {

    get id() {
        return this._id;
    }

    set id(value) {
        this._id = value;
    }

    _buildFromDataSource() {
    }

    constructor(id, data) {
        if(id === null) { id = `${Math.random() * 100000}`; }
        super(id, data, {dataSource: { setWithPriority: async function(){} }});
        this.id = id;
        this._dataSource.ready = true;
    }
}
<commit_msg>Added necessary mock to LocalModel<commit_after>/**
 * Created by Manuel on 22/07/16.
 */

import {Model}      from "../../core/Model";
import {DataSource} from "../DataSource.js";

export class LocalModel extends Model {

    get id() {
        return this._id;
    }

    set id(value) {
        this._id = value;
    }

    _buildFromDataSource() {
    }

    constructor(id, data) {
        if(id === null) { id = `${Math.random() * 100000}`; }
        super(id, data, {dataSource: { setWithPriority: async function(){} }});
        this.id = id;
        this._dataSource.ready = true;
        this._dataSource.remove = () => {};
    }
}
<|endoftext|>


<commit_before>import $ from "jquery";

function checkState(count, hasAssociated) {
  // Remove the tooltip. A new one will be created based on the
  // information provided.
  this.$node.tooltip("destroy");
  if (hasAssociated) {
    this.$node.parent().addClass("disabled");
    // Activate the tooltip
    this.$node.tooltip({
      container: "body",
      placement: "right",
      title: this.$node.data("associatedMsg")
    });
  } else {
    if (count < this.$node.data("enabledAt")) {
      this.$node.parent().addClass("disabled");
      // Activate the tooltip
      this.$node.tooltip({
        container: "body",
        placement: "right",
        title: this.$node.data("enabledMsg")
      });
    } else {
      this.$node.parent().removeClass("disabled");
    }
  }
}

export class SampleCartButton {
  constructor(node, clickHandler) {
    this.$node = $(node);
    this.$node.on("click", clickHandler);
    this.checkState();
  }

  checkState(count = 0) {
    if (count < this.$node.data("enabledAt")) {
      this.$node.prop("disabled", true);
    } else {
      this.$node.prop("disabled", false);
    }
  }
}

export class SampleExportButton {
  constructor(node, clickHandler) {
    const $node = $(node);
    this.$node = $node;
    this.$node.on("click", function() {
      clickHandler.call($node);
    });
    this.checkState();
  }

  checkState(count = 0, hasAssociated = false) {
    checkState.call(this, count, hasAssociated);
  }
}

/**
 * This class represents the state and function of buttons within the
 * project > sample > Sample Tools dropdown menu.
 */
export class SampleDropdownButton {
  /**
   * Link the dom and the EventListener for a button.
   * @param {node} node - actual button DOM node.
   */
  constructor(node) {
    const btn = this;
    this.$node = $(node);

    this.$node.on("click", function() {
      btn.clickHandler();
    });
    this.checkState();
  }

  clickHandler() {
    if (!this.$node.parent().hasClass("disabled")) {
      $("#js-modal-wrapper").modal("show", this.$node);
    }
  }

  /**
   * Check to see if the button should be disabled based upon the
   * number of currently selected samples
   * @param {number} count of selected samples
   * @param {boolean} hasAssociated whether associated projects are being displayed.
   */
  checkState(count = 0, hasAssociated = false) {
    checkState.call(this, count, hasAssociated);
  }
}
<commit_msg>make sure not diabled<commit_after>import $ from "jquery";

function checkState(count, hasAssociated) {
  // Remove the tooltip. A new one will be created based on the
  // information provided.
  this.$node.tooltip("destroy");
  if (hasAssociated) {
    this.$node.parent().addClass("disabled");
    // Activate the tooltip
    this.$node.tooltip({
      container: "body",
      placement: "right",
      title: this.$node.data("associatedMsg")
    });
  } else {
    if (count < this.$node.data("enabledAt")) {
      this.$node.parent().addClass("disabled");
      // Activate the tooltip
      this.$node.tooltip({
        container: "body",
        placement: "right",
        title: this.$node.data("enabledMsg")
      });
    } else {
      this.$node.parent().removeClass("disabled");
    }
  }
}

export class SampleCartButton {
  constructor(node, clickHandler) {
    this.$node = $(node);
    this.$node.on("click", clickHandler);
    this.checkState();
  }

  checkState(count = 0) {
    if (count < this.$node.data("enabledAt")) {
      this.$node.prop("disabled", true);
    } else {
      this.$node.prop("disabled", false);
    }
  }
}

export class SampleExportButton {
  constructor(node, clickHandler) {
    const $node = $(node);
    this.$node = $node;
    this.$node.on("click", function() {
      clickHandler.call($node);
    });
    this.checkState();
  }

  checkState(count = 0, hasAssociated = false) {
    if (!this.$node.parent().hasClass("disabled")) {
      checkState.call(this, count, hasAssociated);
    }
  }
}

/**
 * This class represents the state and function of buttons within the
 * project > sample > Sample Tools dropdown menu.
 */
export class SampleDropdownButton {
  /**
   * Link the dom and the EventListener for a button.
   * @param {node} node - actual button DOM node.
   */
  constructor(node) {
    const btn = this;
    this.$node = $(node);

    this.$node.on("click", function() {
      btn.clickHandler();
    });
    this.checkState();
  }

  clickHandler() {
    if (!this.$node.parent().hasClass("disabled")) {
      $("#js-modal-wrapper").modal("show", this.$node);
    }
  }

  /**
   * Check to see if the button should be disabled based upon the
   * number of currently selected samples
   * @param {number} count of selected samples
   * @param {boolean} hasAssociated whether associated projects are being displayed.
   */
  checkState(count = 0, hasAssociated = false) {
    checkState.call(this, count, hasAssociated);
  }
}
<|endoftext|>


<commit_before>/**
 * ZURB FOUNDATION 5 MULTISELECT PLUGIN
 *
 * @author Andrea Mariani
 * @mail me@andreamariani.net
 * @twitter @andreamariani2k
 * @web http://www.andreamariani.net
 *
 * ** THIS PLUGIN IS IN DEVELOPMENT ** *
 */

(function($) {

	    //toggle for click on zselect, close for click elsewhere, nothing for click on .zselect *
        $(document).on('click', function(e){
			var container = $(".zselect ul");
            if ( container.parent().is(e.target) || container.prev().is(e.target) || ( container.is(':visible') && !container.parent().is(e.target) ) && ( container.has(e.target).length === 0 )  ) {
                container.toggle();
                //console.log(e.target);
            }
        });

        //escape key for close all zselect
        $(window).on('keydown', function(e){
            e = e || window.event;
            if (e.keyCode === 27) {
                $("li.zmsfilter input").val('').keyup(); //clean filter
                $(".zselect ul").hide();
            }
        });

        //click on label toggle input
        $(document).on('click', '.zselect li, .zselect li input:checkbox', function(e){
            var zbefore_change_event = $.Event('zbefore_change');
            $(this).trigger(zbefore_change_event);
            if(zbefore_change_event.result === false) {
                e.preventDefault();
                $(this).attr("checked", false); // hack to keep placeholder text correct
                $(this).trigger('change');
                return;
            }
            if($(e.target).prop("tagName") !== "INPUT"){
                    $("input:checkbox[disabled!='disabled']",this).prop('checked', function( i, val ) { return !val; }).trigger('change');
            }
        });

        //select all and deselect all
        $(document).on('click','.selectall,.deselectall', function(){
           var state = ($(this).hasClass('selectall'))?true:false;
           $(this).parent().find("input:checkbox[disabled!='disabled']").prop('checked', state).change();
        });

        //optgroup
        $(document).on('click','.optgroup', function(){
            var zbefore_optgroup_event = $.Event('zbefore_optgroup_event');
            $(this).trigger(zbefore_optgroup_event);
            if(zbefore_optgroup_event.result === false) {
                return;
            }
           $(this).parent().find(".optgroup_"+$(this).attr('data-optgroup')+" li input:checkbox[disabled!='disabled']").prop('checked', function( i, val ) { return !val; }).change();
        });

        //when resize window + init
        function onResize(reflow){
            $.each( $(".zselect"), function(k,v){
                //if( $(v).find("ul").attr('style') !== undefined && reflow !== true ) return false; //break if already set

                var w = $(v).outerWidth();

                $(v).find("ul").attr('style', 'width:'+w+'px!important;' );

                //var size = Math.max(Math.min(w / (1), parseFloat(20)), parseFloat(11));
                //console.log(size);
                //$(v).find('ul li').css('font-size', size);

                var w_li = $(v).find('ul li:eq(0)').width();
                //console.log(w_li);

            });

        }

        $( window ).resize(function() {
            onResize();
        });

        function refreshPlaceholder(rel, placeholder, selectedText) {
             selectedText = selectedText || "Selected %1 item%s1 of %2 item%s2";
             var checked=$("div#"+rel+" ul li input:checked").length;
             var tot=$("div#"+rel+" ul li input:checkbox").length;

             if(checked>0) {
                 var checkedS = checked > 1 ? "s" : "";
                 var totS = tot > 1 ? "s" : "";
                 var txt = selectedText.replace(/%1/g, checked)
                                       .replace(/%2/g, tot)
                                       .replace(/%s1/g, checkedS)
                                       .replace(/%s2/g, totS);
                 $(".zselect#"+rel+" span.zmshead").text(txt);
             } else {
                 $(".zselect#"+rel+" span.zmshead").html( (placeholder===undefined) ? ' ' : placeholder );
             }
        }

var methods = {
    init : function(options) {

        var id,checked,disabled="",disabledClass="";
        var optgroup=[];
        var optgroup_size,optgroup_id = 0;
        var optgroup_name = false;
        var optgroup_members = 0;

        $.each( $(this),function(k,v){

            id=Math.random().toString(36).substr(2, 9);
            $(v).hide().attr('rel',id);
            $(v).parent().append("

");

            if(options.selectAll!==false){
                var sAllText="Select All";
                var desAllText="Deselect All";
                if(options.selectAllText!==undefined){
                    sAllText=options.selectAllText[0];
                    desAllText=options.selectAllText[1];
                }

                $('#'+id+' ul').append("
"+sAllText+"
");
                $('#'+id+' ul').append("
"+desAllText+"
");
            }

            $.each(v, function(j,z){

                var appendTo;
                if( $(z).parent().attr("label") !== undefined && optgroup.indexOf($(z).parent().attr("label"))===-1 ){
                    optgroup_size = $(z).parent().find('option').size();
                    optgroup_members += optgroup_size;
                    optgroup_name = $(z).parent().attr("label");

                    $('#'+id+' ul').append("
"+$(z).parent().attr("label")+"
");
                    $('#'+id+' ul').append($("
").addClass('optgroup_'+optgroup_id));
                    optgroup.push($(z).parent().attr("label"));
                }
                //console.log( $(z).attr('value') + " " + $(z).text() + " " + $(z).is('[data-selected]') + " " + $(z).is(':selected'));
                //console.log(id);
                //console.log( '#'+id+' ul' );
                checked = ( $(z).is('[data-selected]') || $(z).is(':selected')) ? "checked='checked'" : "";
                dataZ = ( $(z).data("z") !== undefined ) ? 'data-z="' + $(z).data("z") + '"' : "";

                if( $(z).is('[data-disabled]') ){
                    disabled = "disabled='disabled'";
                    disabledClass = "class='disabled'";
                }
                else{
                    disabled = disabledClass = "";
                }

                if( optgroup_name === false ) appendTo = '#'+id+' ul';
                else                          appendTo = '#'+id+' ul div.optgroup_'+optgroup_id;

                $(appendTo).append("
<input value='"+$(z).val()+"' type='checkbox' "+checked+" "+disabled+" "+dataZ+" /> "+$(z).text()+"
");

                if(optgroup_members === j+1) {
                    optgroup_size = 0;
                    optgroup_id ++;
                    optgroup_name = false;
                }

            });
            $('#'+id+' span.zmshead').html( (options.placeholder===undefined) ? ' ' : options.placeholder );
        });

        if(options.filter === true){
            //defaults
            if (options.filterResult === undefined) options.filterResult = true;
            if (options.filterResultText === undefined) options.filterResultText = 'showed';
            var fplaholder = (options.filterPlaceholder !== undefined) ? options.filterPlaceholder : "Filter...";

            var rel = this.attr('rel');
            $("div#"+rel+" ul").prepend('
<input type="text" placeholder="'+fplaholder+'" />
');

            if(options.filterResult === true)
                $("div#"+rel+" ul").append('

');

            $("div#"+rel+" ul li.zmsfilter input").keyup(function(){
                    var value=$(this).val().toLowerCase();
                    var show=0,tot=$("div#"+rel+" ul li input:checkbox").length;
                    $("div#"+rel+" ul li input:checkbox").filter( function(i,v) {
                          //console.log($(v).val());
                          //console.log($(v).parent().text());
                          if( $(v).val().toLowerCase().indexOf(value) === -1 && $(v).parent().text().toLowerCase().indexOf(value) === -1 ){//and text() check...
                               $(v).parent().hide();

                          }
                          else {
                               $(v).parent().show();
                               show++;
                          }

                    });

                    if(options.filterResult === true)
                        $("div#"+rel+" ul li.filterResult").text(options.filterResultText + ' '+show+'/'+tot);

                });
        }//end filter

        if(options.live !== undefined){
            var rel = this.attr('rel');
            $(".zselect#"+rel).on('change','input:checkbox',function(e){
                $(options.live).val( methods.getValue($("select[rel='"+rel+"']")) );
            });
        }//end live

        if(options.get !== undefined){
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            var need = false;
            for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if (pair[0] == options.get) {

                  need = pair[1].replace(',','%2C').split('%2C');

                }
            }

            if(need){
                var rel = this.attr('rel');
                for(var i=0; i<need.length; i++){
                    //console.log(need[i]);
                    $(".zselect#"+rel+" ul li input:checkbox[value='"+need[i]+"']").trigger('click');

                }
                refreshPlaceholder(rel,options.placeholder,options.selectedText);
            }
        }

        // Updates original select after checkbox update
        $(".zselect").on('change', 'input:checkbox', function() {
            var container = $(this).closest('.zselect');
            var rel = container.attr('id');
            refreshPlaceholder(rel, options.placeholder, options.selectedText);

            var select = $('select[rel='+rel+']');
            $.each(container.find('input:checkbox'), function(k, v) {
                if($(v).val() !== undefined){
                    if($(v).prop('checked')) {
                        select.find("option[value='"+$(v).val()+"']").prop("selected", true);
                    } else {
                        select.find("option[value='"+$(v).val()+"']").prop("selected", false);
                    }
                }
            });
            select.trigger('change');
        });

        onResize();

    },

    getValue : function(selector) {
       if(selector===undefined) selector = this;
       var value = new Array();
       var rel   = $(selector).attr('rel');
       $.each( $("div#"+rel+" ul li input"), function(k,v){
          if( $(v).val() !== undefined ){
               if( $(v).prop('checked') )
               value.push($(v).val());
          }
       });
       return value;
    },

    open : function( ) {
        $("div#"+$(this).attr('rel')+" ul").show();
    },
    close : function( ) {
        $("div#"+$(this).attr('rel')+" ul").hide();
    },

    disable : function (val,state){ //console.log(state);
        if(val!==undefined){
            if(state) $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").attr('disabled','disabled');
            else      $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").removeAttr('disabled');
        }
        else{
            if(state) $("div#"+$(this).attr('rel')+" ul li input:checkbox").attr('disabled','disabled');
            else      $("div#"+$(this).attr('rel')+" ul li input:checkbox").removeAttr('disabled');
        }
    },
    set : function (val,checked){
        $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").prop('checked', checked).change();
    },
    uncheckall_inpage : function( ) {
        $(".zselect ul li input:checkbox").prop('checked', false).change();
    },
    checkall_inpage : function( ) {
        $(".zselect ul li input:checkbox").prop('checked', true).change();
    },
    checkall : function( ) {
        $("div#"+$(this).attr('rel')+" ul li input:checkbox").prop('checked', true).change();
    },
    uncheckall : function( ) {
        $("div#"+$(this).attr('rel')+" ul li input:checkbox").prop('checked', false).change();
    },
    destroy : function (val){
        $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").parent().remove();
    },
    reflow : function(){
        onResize(true);
    },

    add : function(option, pos){
        var position = pos || 'append';
        var checked='', disabled='', disabledClass='';

        if(option.checked)  checked=' checked="checked" ';
        if(option.disabled) {disabled=' disabled="disabled" '; disabledClass=' class="disabled" ';}

        if(position === 'append') $("div#"+$(this).attr('rel')+" ul").append("
<input value='"+option.value+"' type='checkbox' "+checked+" "+disabled+" /> "+option.text+"
");
        else {
            if(position === 'prepend'){
               $("
<input value='"+option.value+"' type='checkbox' "+checked+" "+disabled+" /> "+option.text+"
").insertAfter($("div#"+$(this).attr('rel')+" ul li.deselectall"));
            }
            else{
               $("
<input value='"+option.value+"' type='checkbox' "+checked+" "+disabled+" /> "+option.text+"
").insertAfter($("div#"+$(this).attr('rel')+" ul li input[value='"+position.substring(1)+"']").closest('li'));
            }
        }

    }

    //,update : function( content ) {  }
    };

$.fn.zmultiselect = function(methodOrOptions) {
    if ( methods[methodOrOptions] ) {
        return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
        return methods.init.apply( this, arguments );
    } else {
        $.error( 'Method ' +  methodOrOptions + ' does not exist on zmultiselect' );
    }
    };

})( jQuery );
<commit_msg>fix to properly handle events<commit_after>/**
 * ZURB FOUNDATION 5 MULTISELECT PLUGIN
 *
 * @author Andrea Mariani
 * @mail me@andreamariani.net
 * @twitter @andreamariani2k
 * @web http://www.andreamariani.net
 *
 * ** THIS PLUGIN IS IN DEVELOPMENT ** *
 */

(function($) {

	    //toggle for click on zselect, close for click elsewhere, nothing for click on .zselect *
        $(document).on('click', function(e){
			var container = $(".zselect ul");
            if ( container.parent().is(e.target) || container.prev().is(e.target) || ( container.is(':visible') && !container.parent().is(e.target) ) && ( container.has(e.target).length === 0 )  ) {
                container.toggle();
                //console.log(e.target);
            }
        });

        //escape key for close all zselect
        $(window).on('keydown', function(e){
            e = e || window.event;
            if (e.keyCode === 27) {
                $("li.zmsfilter input").val('').keyup(); //clean filter
                $(".zselect ul").hide();
            }
        });

        //click on label toggle input
        $(document).on('click', '.zselect li, .zselect li input:checkbox', function(e){
            var zbefore_change_event = $.Event('zbefore_change', {'target': e.target});
            $(this).trigger(zbefore_change_event);
            if(zbefore_change_event.result === false) {
                e.preventDefault();
                if($(this).prop("tagName") == 'LI'){
                    $(this).children().attr("checked", false);
                    $(this).children().trigger('change')
                }
                else{
                    $(this).attr("checked", false); // hack to keep placeholder text correct
                    $(this).trigger('change');
                }
                return;
            }
            $(this).trigger('change');
            if($(e.target).prop("tagName") !== "INPUT"){
                    $("input:checkbox[disabled!='disabled']",this).prop('checked', function( i, val ) { return !val; }).trigger('change');
            }
        });

        //select all and deselect all
        $(document).on('click','.selectall,.deselectall', function(){
           var state = ($(this).hasClass('selectall'))?true:false;
           $(this).parent().find("input:checkbox[disabled!='disabled']").prop('checked', state).change();
        });

        //optgroup
        $(document).on('click','.optgroup', function(){
            var zbefore_optgroup_event = $.Event('zbefore_optgroup_event');
            $(this).trigger(zbefore_optgroup_event);
            if(zbefore_optgroup_event.result === false) {
                return;
            }
           $(this).parent().find(".optgroup_"+$(this).attr('data-optgroup')+" li input:checkbox[disabled!='disabled']").prop('checked', function( i, val ) { return !val; }).change();
        });

        //when resize window + init
        function onResize(reflow){
            $.each( $(".zselect"), function(k,v){
                //if( $(v).find("ul").attr('style') !== undefined && reflow !== true ) return false; //break if already set

                var w = $(v).outerWidth();

                $(v).find("ul").attr('style', 'width:'+w+'px!important;' );

                //var size = Math.max(Math.min(w / (1), parseFloat(20)), parseFloat(11));
                //console.log(size);
                //$(v).find('ul li').css('font-size', size);

                var w_li = $(v).find('ul li:eq(0)').width();
                //console.log(w_li);

            });

        }

        $( window ).resize(function() {
            onResize();
        });

        function refreshPlaceholder(rel, placeholder, selectedText) {
             selectedText = selectedText || "Selected %1 item%s1 of %2 item%s2";
             var checked=$("div#"+rel+" ul li input:checked").length;
             var tot=$("div#"+rel+" ul li input:checkbox").length;

             if(checked>0) {
                 var checkedS = checked > 1 ? "s" : "";
                 var totS = tot > 1 ? "s" : "";
                 var txt = selectedText.replace(/%1/g, checked)
                                       .replace(/%2/g, tot)
                                       .replace(/%s1/g, checkedS)
                                       .replace(/%s2/g, totS);
                 $(".zselect#"+rel+" span.zmshead").text(txt);
             } else {
                 $(".zselect#"+rel+" span.zmshead").html( (placeholder===undefined) ? ' ' : placeholder );
             }
        }

var methods = {
    init : function(options) {

        var id,checked,disabled="",disabledClass="";
        var optgroup=[];
        var optgroup_size,optgroup_id = 0;
        var optgroup_name = false;
        var optgroup_members = 0;

        $.each( $(this),function(k,v){

            id=Math.random().toString(36).substr(2, 9);
            $(v).hide().attr('rel',id);
            $(v).parent().append("

");

            if(options.selectAll!==false){
                var sAllText="Select All";
                var desAllText="Deselect All";
                if(options.selectAllText!==undefined){
                    sAllText=options.selectAllText[0];
                    desAllText=options.selectAllText[1];
                }

                $('#'+id+' ul').append("
"+sAllText+"
");
                $('#'+id+' ul').append("
"+desAllText+"
");
            }

            $.each(v, function(j,z){

                var appendTo;
                if( $(z).parent().attr("label") !== undefined && optgroup.indexOf($(z).parent().attr("label"))===-1 ){
                    optgroup_size = $(z).parent().find('option').size();
                    optgroup_members += optgroup_size;
                    optgroup_name = $(z).parent().attr("label");

                    $('#'+id+' ul').append("
"+$(z).parent().attr("label")+"
");
                    $('#'+id+' ul').append($("
").addClass('optgroup_'+optgroup_id));
                    optgroup.push($(z).parent().attr("label"));
                }
                //console.log( $(z).attr('value') + " " + $(z).text() + " " + $(z).is('[data-selected]') + " " + $(z).is(':selected'));
                //console.log(id);
                //console.log( '#'+id+' ul' );
                checked = ( $(z).is('[data-selected]') || $(z).is(':selected')) ? "checked='checked'" : "";
                dataZ = ( $(z).data("z") !== undefined ) ? 'data-z="' + $(z).data("z") + '"' : "";

                if( $(z).is('[data-disabled]') ){
                    disabled = "disabled='disabled'";
                    disabledClass = "class='disabled'";
                }
                else{
                    disabled = disabledClass = "";
                }

                if( optgroup_name === false ) appendTo = '#'+id+' ul';
                else                          appendTo = '#'+id+' ul div.optgroup_'+optgroup_id;

                $(appendTo).append("
<input value='"+$(z).val()+"' type='checkbox' "+checked+" "+disabled+" "+dataZ+" /> "+$(z).text()+"
");

                if(optgroup_members === j+1) {
                    optgroup_size = 0;
                    optgroup_id ++;
                    optgroup_name = false;
                }

            });
            $('#'+id+' span.zmshead').html( (options.placeholder===undefined) ? ' ' : options.placeholder );
        });

        if(options.filter === true){
            //defaults
            if (options.filterResult === undefined) options.filterResult = true;
            if (options.filterResultText === undefined) options.filterResultText = 'showed';
            var fplaholder = (options.filterPlaceholder !== undefined) ? options.filterPlaceholder : "Filter...";

            var rel = this.attr('rel');
            $("div#"+rel+" ul").prepend('
<input type="text" placeholder="'+fplaholder+'" />
');

            if(options.filterResult === true)
                $("div#"+rel+" ul").append('

');

            $("div#"+rel+" ul li.zmsfilter input").keyup(function(){
                    var value=$(this).val().toLowerCase();
                    var show=0,tot=$("div#"+rel+" ul li input:checkbox").length;
                    $("div#"+rel+" ul li input:checkbox").filter( function(i,v) {
                          //console.log($(v).val());
                          //console.log($(v).parent().text());
                          if( $(v).val().toLowerCase().indexOf(value) === -1 && $(v).parent().text().toLowerCase().indexOf(value) === -1 ){//and text() check...
                               $(v).parent().hide();

                          }
                          else {
                               $(v).parent().show();
                               show++;
                          }

                    });

                    if(options.filterResult === true)
                        $("div#"+rel+" ul li.filterResult").text(options.filterResultText + ' '+show+'/'+tot);

                });
        }//end filter

        if(options.live !== undefined){
            var rel = this.attr('rel');
            $(".zselect#"+rel).on('change','input:checkbox',function(e){
                $(options.live).val( methods.getValue($("select[rel='"+rel+"']")) );
            });
        }//end live

        if(options.get !== undefined){
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            var need = false;
            for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if (pair[0] == options.get) {

                  need = pair[1].replace(',','%2C').split('%2C');

                }
            }

            if(need){
                var rel = this.attr('rel');
                for(var i=0; i<need.length; i++){
                    //console.log(need[i]);
                    $(".zselect#"+rel+" ul li input:checkbox[value='"+need[i]+"']").trigger('click');

                }
                refreshPlaceholder(rel,options.placeholder,options.selectedText);
            }
        }

        // Updates original select after checkbox update
        $(".zselect").on('change', 'input:checkbox', function() {
            var container = $(this).closest('.zselect');
            var rel = container.attr('id');
            refreshPlaceholder(rel, options.placeholder, options.selectedText);

            var select = $('select[rel='+rel+']');
            $.each(container.find('input:checkbox'), function(k, v) {
                if($(v).val() !== undefined){
                    if($(v).prop('checked')) {
                        select.find("option[value='"+$(v).val()+"']").prop("selected", true);
                    } else {
                        select.find("option[value='"+$(v).val()+"']").prop("selected", false);
                    }
                }
            });
            select.trigger('change');
        });

        onResize();

    },

    getValue : function(selector) {
       if(selector===undefined) selector = this;
       var value = new Array();
       var rel   = $(selector).attr('rel');
       $.each( $("div#"+rel+" ul li input"), function(k,v){
          if( $(v).val() !== undefined ){
               if( $(v).prop('checked') )
               value.push($(v).val());
          }
       });
       return value;
    },

    open : function( ) {
        $("div#"+$(this).attr('rel')+" ul").show();
    },
    close : function( ) {
        $("div#"+$(this).attr('rel')+" ul").hide();
    },

    disable : function (val,state){ //console.log(state);
        if(val!==undefined){
            if(state) $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").attr('disabled','disabled');
            else      $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").removeAttr('disabled');
        }
        else{
            if(state) $("div#"+$(this).attr('rel')+" ul li input:checkbox").attr('disabled','disabled');
            else      $("div#"+$(this).attr('rel')+" ul li input:checkbox").removeAttr('disabled');
        }
    },
    set : function (val,checked){
        $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").prop('checked', checked).change();
    },
    uncheckall_inpage : function( ) {
        $(".zselect ul li input:checkbox").prop('checked', false).change();
    },
    checkall_inpage : function( ) {
        $(".zselect ul li input:checkbox").prop('checked', true).change();
    },
    checkall : function( ) {
        $("div#"+$(this).attr('rel')+" ul li input:checkbox").prop('checked', true).change();
    },
    uncheckall : function( ) {
        $("div#"+$(this).attr('rel')+" ul li input:checkbox").prop('checked', false).change();
    },
    destroy : function (val){
        $("div#"+$(this).attr('rel')+" ul li input:checkbox[value='"+val+"']").parent().remove();
    },
    reflow : function(){
        onResize(true);
    },

    add : function(option, pos){
        var position = pos || 'append';
        var checked='', disabled='', disabledClass='';

        if(option.checked)  checked=' checked="checked" ';
        if(option.disabled) {disabled=' disabled="disabled" '; disabledClass=' class="disabled" ';}

        if(position === 'append') $("div#"+$(this).attr('rel')+" ul").append("
<input value='"+option.value+"' type='checkbox' "+checked+" "+disabled+" /> "+option.text+"
");
        else {
            if(position === 'prepend'){
               $("
<input value='"+option.value+"' type='checkbox' "+checked+" "+disabled+" /> "+option.text+"
").insertAfter($("div#"+$(this).attr('rel')+" ul li.deselectall"));
            }
            else{
               $("
<input value='"+option.value+"' type='checkbox' "+checked+" "+disabled+" /> "+option.text+"
").insertAfter($("div#"+$(this).attr('rel')+" ul li input[value='"+position.substring(1)+"']").closest('li'));
            }
        }

    }

    //,update : function( content ) {  }
    };

$.fn.zmultiselect = function(methodOrOptions) {
    if ( methods[methodOrOptions] ) {
        return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
        return methods.init.apply( this, arguments );
    } else {
        $.error( 'Method ' +  methodOrOptions + ' does not exist on zmultiselect' );
    }
    };

})( jQuery );
<|endoftext|>


<commit_before>const transform = require('gulp-transform-js-ast');
const rename = require('gulp-es6-imports-renamer');
const replace = require('gulp-replace');

const CORE_PACKAGE_NAME = 'angular2-modal';
const CORE_IMPORT_REGEX = /^(.*\.\.?\/components\/angular2-modal)(.*)$/;

function renameFn(originalPath, parentPath, callback) {
  var match = CORE_IMPORT_REGEX.exec(originalPath);
  if ( match !== null) {
    callback(null, originalPath.replace(CORE_IMPORT_REGEX, `${CORE_PACKAGE_NAME}$2`));
  } else {
    callback(null, originalPath);
  }
}

const visitCallExpression = (function() {
  function isRequireMethod (path) {
    var node = path.value;

    return node.type === 'CallExpression' &&
      node.callee &&
      node.callee.type === 'Identifier' &&
      node.callee.name === 'require';
  }

  function isLiteral(path) {
    var args = path.value.arguments;
    return args &&
      args.length === 1 &&
      args[0].type === 'Literal';
  }

  function isCandidate(path) {
    return isRequireMethod(path) && isLiteral(path);
  }

  return function visitCallExpression(path) {
    if (isCandidate(path)) {
      var match,
        arg = path.value.arguments["0"];
      if ((match = CORE_IMPORT_REGEX.exec(arg.value)) !== null) {
        arg.value = arg.value.replace(CORE_IMPORT_REGEX, `${CORE_PACKAGE_NAME}$2`);
      }
    }
    return path.value;
  }
})();

function tsDefinitionImportRename() {
  const CORE_IMPORT_REGEX = /^(import {.+} from ['"])(.*\/components\/angular2-modal)(['"];?)$/m;
  return replace(CORE_IMPORT_REGEX, `$1${CORE_PACKAGE_NAME}$3`);
}

module.exports.tsDefinitionImportRename = tsDefinitionImportRename();
module.exports.es6ImportRename = rename({renameFn: renameFn});
module.exports.es5RequireVisitor = transform( { visitCallExpression: visitCallExpression } );
<commit_msg>fix: be greedy when replacing d.ts imports<commit_after>const transform = require('gulp-transform-js-ast');
const rename = require('gulp-es6-imports-renamer');
const replace = require('gulp-replace');

const CORE_PACKAGE_NAME = 'angular2-modal';
const CORE_IMPORT_REGEX = /^(.*\.\.?\/components\/angular2-modal)(.*)$/;

function renameFn(originalPath, parentPath, callback) {
  var match = CORE_IMPORT_REGEX.exec(originalPath);
  if ( match !== null) {
    callback(null, originalPath.replace(CORE_IMPORT_REGEX, `${CORE_PACKAGE_NAME}$2`));
  } else {
    callback(null, originalPath);
  }
}

const visitCallExpression = (function() {
  function isRequireMethod (path) {
    var node = path.value;

    return node.type === 'CallExpression' &&
      node.callee &&
      node.callee.type === 'Identifier' &&
      node.callee.name === 'require';
  }

  function isLiteral(path) {
    var args = path.value.arguments;
    return args &&
      args.length === 1 &&
      args[0].type === 'Literal';
  }

  function isCandidate(path) {
    return isRequireMethod(path) && isLiteral(path);
  }

  return function visitCallExpression(path) {
    if (isCandidate(path)) {
      var match,
        arg = path.value.arguments["0"];
      if ((match = CORE_IMPORT_REGEX.exec(arg.value)) !== null) {
        arg.value = arg.value.replace(CORE_IMPORT_REGEX, `${CORE_PACKAGE_NAME}$2`);
      }
    }
    return path.value;
  }
})();

function tsDefinitionImportRename() {
  const CORE_IMPORT_REGEX = /^(import {.+} from ['"])(.*\/components\/angular2-modal)(['"];?)$/mg;
  return replace(CORE_IMPORT_REGEX, `$1${CORE_PACKAGE_NAME}$3`);
}

module.exports.tsDefinitionImportRename = tsDefinitionImportRename();
module.exports.es6ImportRename = rename({renameFn: renameFn});
module.exports.es5RequireVisitor = transform( { visitCallExpression: visitCallExpression } );
<|endoftext|>


<commit_before>/**
Utilities for reading / writing fields.
**/
OpenAssessment.Fields = {
    stringField: function(sel, value) {
        if (value !== undefined) { sel.val(value); }
        return sel.val();
    },

    booleanField: function(sel, value) {
        if (value !== undefined) { sel.prop("checked", value); }
        return sel.prop("checked");
    },
};

/**
Integer input.

Args:
    inputSel (JQuery selector or DOM element): The input field.

Keyword args:
    min (int): The minimum value allowed in the input.
    max (int): The maximum value allowed in the input.

**/
OpenAssessment.IntField = function(inputSel, restrictions) {
    this.max = restrictions.max;
    this.min = restrictions.min;
    this.input = $(inputSel);
};

OpenAssessment.IntField.prototype = {

    /**
    Retrieve the integer value from the input.
    Decimal values will be truncated, and non-numeric
    values will become NaN.

    Returns:
        integer or NaN
    **/
    get: function() {
        return parseInt(this.input.val().trim(), 10);
    },

    /**
    Set the input value.

    Args:
        val (int or string)

    **/
    set: function(val) {
        this.input.val(val);
    },

    /**
    Mark validation errors if the field does not satisfy the restrictions.
    Fractional values are not considered valid integers.

    This will trim whitespace from the field, so "   34  " would be considered
    a valid input.

    Returns:
        Boolean indicating whether the field's value is valid.

    **/
    validate: function() {
        var value = this.get();
        var isValid = !isNaN(value) && value >= this.min && value <= this.max;

        // Decimal values not allowed
        if (this.input.val().indexOf(".") !== -1) {
            isValid = false;
        }

        if (!isValid) {
            this.input.addClass("openassessment_highlighted_field");
        }
        return isValid;
    },

    /**
    Clear any validation errors from the UI.
    **/
    clearValidationErrors: function() {
        this.input.removeClass("openassessment_highlighted_field");
    },

    /**
    Return a list of validation errors currently displayed
    in the UI.  Mainly useful for testing.

    Returns:
        list of strings

    **/
    validationErrors: function() {
        var hasError = this.input.hasClass("openassessment_highlighted_field");
        return hasError ? ["Int field is invalid"] : [];
    },
};

/**
Show and hide elements based on a checkbox.

Args:
    checkboxSel (JQuery selector): The checkbox used to toggle whether sections
        are shown or hidden.
    shownSel (JQuery selector): The section to show when the checkbox is checked.
    hiddenSel (JQuery selector): The section to show when the checkbox is unchecked.
    notifier (OpenAssessment.Notifier): Receives notifications when the checkbox state changes.

Sends the following notifications:
    * toggleOn
    * toggleOff
**/
OpenAssessment.ToggleControl = function(checkboxSel, shownSel, hiddenSel, notifier) {
    this.checkbox = checkboxSel;
    this.shownSection = shownSel;
    this.hiddenSection = hiddenSel;
    this.notifier = notifier;
};

OpenAssessment.ToggleControl.prototype = {
    /**
    Install the event handler for the checkbox,
    passing in the toggle control object as the event data.

    Args:
        checkboxSelector (string): The CSS selector string for the checkbox.

    Returns:
        OpenAssessment.ToggleControl
    **/
    install: function(checkboxSelector) {
        this.checkbox.change(
            this, function(event) {
                var control = event.data;
                if (this.checked) {
                    control.notifier.notificationFired('toggleOn', {});
                    control.show();
                }
                else {
                    control.notifier.notificationFired('toggleOff', {});
                    control.hide();
                }
            }
        );
        return this;
    },

    show: function() {
        this.shownSection.removeClass('is--hidden');
        this.hiddenSection.addClass('is--hidden');
    },

    hide: function() {
        this.shownSection.addClass('is--hidden');
        this.hiddenSection.removeClass('is--hidden');
    }
};

/**
Date and time input fields.

Args:
    element (DOM element): The parent element of the control inputs.
    datePicker (string): The CSS selector for the date input field.
    timePicker (string): The CSS selector for the time input field.

**/
OpenAssessment.DatetimeControl = function(element, datePicker, timePicker) {
    this.element = element;
    this.datePicker = datePicker;
    this.timePicker = timePicker;
};

OpenAssessment.DatetimeControl.prototype = {
    /**
    Configure the date and time picker inputs.

    Returns:
        OpenAssessment.DatetimeControl

    **/
    install: function() {
        var dateString = $(this.datePicker, this.element).val();
        $(this.datePicker, this.element).datepicker({ showButtonPanel: true })
            .datepicker("option", "dateFormat", "yy-mm-dd")
            .datepicker("setDate", dateString);
        $(this.timePicker, this.element).timepicker({
            timeFormat: 'H:i',
            step: 60
        });
        return this;
    },

    /**
    Get or set the date and time.

    Args:
        dateString (string, optional): If provided, set the date (YYYY-MM-DD).
        timeString (string, optional): If provided, set the time (HH:MM, 24-hour clock).

    Returns:
        ISO-formatted datetime string.

    **/
    datetime: function(dateString, timeString) {
        var datePickerSel = $(this.datePicker, this.element);
        var timePickerSel = $(this.timePicker, this.element);
        if (typeof(dateString) !== "undefined") { datePickerSel.val(dateString); }
        if (typeof(timeString) !== "undefined") { timePickerSel.val(timeString); }
        return datePickerSel.val() + "T" + timePickerSel.val();
    },

    /**
    Mark validation errors.

    Returns:
        Boolean indicating whether the fields are valid.

    **/
    validate: function() {
        var dateString = $(this.datePicker, this.element).val();
        var timeString = $(this.timePicker, this.element).val();

        //date validation
        var isDateValid = false;

        try {
            var parsedDate = $.datepicker.parseDate($.datepicker.ISO_8601, dateString);
            isDateValid = parsedDate instanceof Date;
        } catch (err) {
            // parseDate throws error if date is not in expected format.
        }
        if (!isDateValid) {
            $(this.datePicker, this.element).addClass("openassessment_highlighted_field");
        }

        //time validation
        var matches = timeString.match(/^\d{2}:\d{2}$/g);
        var isTimeValid = (matches !== null);
        if(!isTimeValid) {
            $(this.timePicker, this.element).addClass("openassessment_highlighted_field");
        }

        return (isDateValid && isTimeValid);
    },

    /**
    Clear all validation errors from the UI.
    **/
    clearValidationErrors: function() {
        $(this.datePicker, this.element).removeClass("openassessment_highlighted_field");
        $(this.timePicker, this.element).removeClass("openassessment_highlighted_field");
    },

   /**
    Return a list of validation errors visible in the UI.
    Mainly useful for testing.

    Returns:
        list of string

    **/
    validationErrors: function() {
        var errors = [];
        var dateHasError = $(this.datePicker, this.element).hasClass("openassessment_highlighted_field");
        var timeHasError = $(this.timePicker, this.element).hasClass("openassessment_highlighted_field");

        if (dateHasError) { errors.push("Date is invalid"); }
        if (timeHasError) { errors.push("Time is invalid"); }

        return errors;
    },
};<commit_msg>Adding more readable comments to catch block.<commit_after>/**
Utilities for reading / writing fields.
**/
OpenAssessment.Fields = {
    stringField: function(sel, value) {
        if (value !== undefined) { sel.val(value); }
        return sel.val();
    },

    booleanField: function(sel, value) {
        if (value !== undefined) { sel.prop("checked", value); }
        return sel.prop("checked");
    },
};

/**
Integer input.

Args:
    inputSel (JQuery selector or DOM element): The input field.

Keyword args:
    min (int): The minimum value allowed in the input.
    max (int): The maximum value allowed in the input.

**/
OpenAssessment.IntField = function(inputSel, restrictions) {
    this.max = restrictions.max;
    this.min = restrictions.min;
    this.input = $(inputSel);
};

OpenAssessment.IntField.prototype = {

    /**
    Retrieve the integer value from the input.
    Decimal values will be truncated, and non-numeric
    values will become NaN.

    Returns:
        integer or NaN
    **/
    get: function() {
        return parseInt(this.input.val().trim(), 10);
    },

    /**
    Set the input value.

    Args:
        val (int or string)

    **/
    set: function(val) {
        this.input.val(val);
    },

    /**
    Mark validation errors if the field does not satisfy the restrictions.
    Fractional values are not considered valid integers.

    This will trim whitespace from the field, so "   34  " would be considered
    a valid input.

    Returns:
        Boolean indicating whether the field's value is valid.

    **/
    validate: function() {
        var value = this.get();
        var isValid = !isNaN(value) && value >= this.min && value <= this.max;

        // Decimal values not allowed
        if (this.input.val().indexOf(".") !== -1) {
            isValid = false;
        }

        if (!isValid) {
            this.input.addClass("openassessment_highlighted_field");
        }
        return isValid;
    },

    /**
    Clear any validation errors from the UI.
    **/
    clearValidationErrors: function() {
        this.input.removeClass("openassessment_highlighted_field");
    },

    /**
    Return a list of validation errors currently displayed
    in the UI.  Mainly useful for testing.

    Returns:
        list of strings

    **/
    validationErrors: function() {
        var hasError = this.input.hasClass("openassessment_highlighted_field");
        return hasError ? ["Int field is invalid"] : [];
    },
};

/**
Show and hide elements based on a checkbox.

Args:
    checkboxSel (JQuery selector): The checkbox used to toggle whether sections
        are shown or hidden.
    shownSel (JQuery selector): The section to show when the checkbox is checked.
    hiddenSel (JQuery selector): The section to show when the checkbox is unchecked.
    notifier (OpenAssessment.Notifier): Receives notifications when the checkbox state changes.

Sends the following notifications:
    * toggleOn
    * toggleOff
**/
OpenAssessment.ToggleControl = function(checkboxSel, shownSel, hiddenSel, notifier) {
    this.checkbox = checkboxSel;
    this.shownSection = shownSel;
    this.hiddenSection = hiddenSel;
    this.notifier = notifier;
};

OpenAssessment.ToggleControl.prototype = {
    /**
    Install the event handler for the checkbox,
    passing in the toggle control object as the event data.

    Args:
        checkboxSelector (string): The CSS selector string for the checkbox.

    Returns:
        OpenAssessment.ToggleControl
    **/
    install: function(checkboxSelector) {
        this.checkbox.change(
            this, function(event) {
                var control = event.data;
                if (this.checked) {
                    control.notifier.notificationFired('toggleOn', {});
                    control.show();
                }
                else {
                    control.notifier.notificationFired('toggleOff', {});
                    control.hide();
                }
            }
        );
        return this;
    },

    show: function() {
        this.shownSection.removeClass('is--hidden');
        this.hiddenSection.addClass('is--hidden');
    },

    hide: function() {
        this.shownSection.addClass('is--hidden');
        this.hiddenSection.removeClass('is--hidden');
    }
};

/**
Date and time input fields.

Args:
    element (DOM element): The parent element of the control inputs.
    datePicker (string): The CSS selector for the date input field.
    timePicker (string): The CSS selector for the time input field.

**/
OpenAssessment.DatetimeControl = function(element, datePicker, timePicker) {
    this.element = element;
    this.datePicker = datePicker;
    this.timePicker = timePicker;
};

OpenAssessment.DatetimeControl.prototype = {
    /**
    Configure the date and time picker inputs.

    Returns:
        OpenAssessment.DatetimeControl

    **/
    install: function() {
        var dateString = $(this.datePicker, this.element).val();
        $(this.datePicker, this.element).datepicker({ showButtonPanel: true })
            .datepicker("option", "dateFormat", "yy-mm-dd")
            .datepicker("setDate", dateString);
        $(this.timePicker, this.element).timepicker({
            timeFormat: 'H:i',
            step: 60
        });
        return this;
    },

    /**
    Get or set the date and time.

    Args:
        dateString (string, optional): If provided, set the date (YYYY-MM-DD).
        timeString (string, optional): If provided, set the time (HH:MM, 24-hour clock).

    Returns:
        ISO-formatted datetime string.

    **/
    datetime: function(dateString, timeString) {
        var datePickerSel = $(this.datePicker, this.element);
        var timePickerSel = $(this.timePicker, this.element);
        if (typeof(dateString) !== "undefined") { datePickerSel.val(dateString); }
        if (typeof(timeString) !== "undefined") { timePickerSel.val(timeString); }
        return datePickerSel.val() + "T" + timePickerSel.val();
    },

    /**
    Mark validation errors.

    Returns:
        Boolean indicating whether the fields are valid.

    **/
    validate: function() {
        var dateString = $(this.datePicker, this.element).val();
        var timeString = $(this.timePicker, this.element).val();

        //date validation
        var isDateValid = false;

        try {
            var parsedDate = $.datepicker.parseDate($.datepicker.ISO_8601, dateString);
            isDateValid = parsedDate instanceof Date;
        } catch (err) {
            // parseDate function throws error if date is not in expected format.
            // isDateValid flag would remain false.
        }
        if (!isDateValid) {
            $(this.datePicker, this.element).addClass("openassessment_highlighted_field");
        }

        //time validation
        var matches = timeString.match(/^\d{2}:\d{2}$/g);
        var isTimeValid = (matches !== null);
        if(!isTimeValid) {
            $(this.timePicker, this.element).addClass("openassessment_highlighted_field");
        }

        return (isDateValid && isTimeValid);
    },

    /**
    Clear all validation errors from the UI.
    **/
    clearValidationErrors: function() {
        $(this.datePicker, this.element).removeClass("openassessment_highlighted_field");
        $(this.timePicker, this.element).removeClass("openassessment_highlighted_field");
    },

   /**
    Return a list of validation errors visible in the UI.
    Mainly useful for testing.

    Returns:
        list of string

    **/
    validationErrors: function() {
        var errors = [];
        var dateHasError = $(this.datePicker, this.element).hasClass("openassessment_highlighted_field");
        var timeHasError = $(this.timePicker, this.element).hasClass("openassessment_highlighted_field");

        if (dateHasError) { errors.push("Date is invalid"); }
        if (timeHasError) { errors.push("Time is invalid"); }

        return errors;
    },
};<|endoftext|>


<commit_before>#!/usr/bin/env node

const resolvePath = require('path').resolve
const kebabCase = require('lodash').kebabCase
const inquirer = require('inquirer')
const appGenerator = require('../generators/app')
const args = process.argv.slice(2)

if (!args[0]) {
  inquirer.prompt({
    type: 'input',
    name: 'projectName',
    message: 'What is your project name?'
  }).then(props => {
    process.env.PROJECT_PATH = resolvePath(process.cwd(), props.projectName)
    appGenerator({projectName: props.projectName})
  })
} else {
  if (args.length === 1) {
    var projectName = kebabCase(args[0])
    process.env.PROJECT_PATH = resolvePath(process.cwd(), projectName)
    appGenerator({projectName})
  } else if (args[1] === 'from' && args[2]) {
    projectName = kebabCase(args[0])
    const templateRepo = args[2]
    process.env.PROJECT_PATH = resolvePath(process.cwd(), projectName)
    appGenerator({projectName, templateRepo})
  }
}
<commit_msg>Help option working when using new<commit_after>#!/usr/bin/env node

const resolvePath = require('path').resolve
const kebabCase = require('lodash').kebabCase
const help = require('./help.js')
const R = require('ramda')
const inquirer = require('inquirer')
const appGenerator = require('../generators/app')
const args = process.argv.slice(2)

const helpOptions = R.intersection(['--help', '-h'])
const notEmpty = R.complement(R.isEmpty)
const hasHelp = R.pipe(
  helpOptions,
  notEmpty
)

if (hasHelp(args)) {
  console.log(help.newApp)
  process.exit(0)
}

if (!args[0]) {
  inquirer.prompt({
    type: 'input',
    name: 'projectName',
    message: 'What is your project name?'
  }).then(props => {
    process.env.PROJECT_PATH = resolvePath(process.cwd(), props.projectName)
    appGenerator({projectName: props.projectName})
  })
} else {
  if (args.length === 1) {
    var projectName = kebabCase(args[0])
    process.env.PROJECT_PATH = resolvePath(process.cwd(), projectName)
    appGenerator({projectName})
  } else if (args[1] === 'from' && args[2]) {
    projectName = kebabCase(args[0])
    const templateRepo = args[2]
    process.env.PROJECT_PATH = resolvePath(process.cwd(), projectName)
    appGenerator({projectName, templateRepo})
  }
}
<|endoftext|>


<commit_before>"use strict";

import * as JSSynth from "./jssynth";

class Serializer {
  constructor() {};

  static serializeInstrument(instrument) {
    let filterCutoff = parseInt(instrument.filterCutoff, 10);

    let serializedConfig = {
      oscillators: [
        {
          waveform: instrument.waveform1,
          octave: parseInt(instrument.waveform1Octave),
          detune: 0,
        },
        {
          waveform: instrument.waveform2,
          octave: parseInt(instrument.waveform2Octave),
          detune: parseInt(instrument.waveform2Detune),
        }
      ],
      lfo: {
        waveform:  instrument.lfoWaveform,
        frequency: parseFloat(instrument.lfoFrequency),
        amplitude: parseInt(instrument.lfoAmplitude, 10),
      },
      filter: {
        cutoff:    filterCutoff,
        resonance: parseInt(instrument.filterResonance, 10),
        mode: instrument.filterModulator,
        lfo: {
          waveform:  instrument.filterLFOWaveform,
          frequency: parseFloat(instrument.filterLFOFrequency),
          amplitude: parseFloat(instrument.filterLFOAmplitude) * filterCutoff,
        },
        envelope: {
          attack:  parseFloat(instrument.filterEnvelopeAttack),
          decay:   parseFloat(instrument.filterEnvelopeDecay),
          sustain: parseFloat(instrument.filterEnvelopeSustain),
          release: parseFloat(instrument.filterEnvelopeRelease),
        },
      },
      envelope: {
        attack:  parseFloat(instrument.envelopeAttack),
        decay:   parseFloat(instrument.envelopeDecay),
        sustain: parseFloat(instrument.envelopeSustain),
        release: parseFloat(instrument.envelopeRelease),
      },
    };

    return new JSSynth.Instrument(serializedConfig);
  };

  static serializePatterns(patterns) {
    let serializedPatterns = {};

    patterns.forEach(function(pattern) {
      let serializedRows = [];

      pattern.rows.forEach(function(row) {
        let sequence;
        let rawSequenceString;

        rawSequenceString = row.notes.map(function(note) { return note.name; }).join(' ');
        sequence = JSSynth.SequenceParser.parse(rawSequenceString);
        serializedRows.push(sequence);
      });

      serializedPatterns[pattern.id] = serializedRows;
    });

    return serializedPatterns;
  };

  static trackByID(tracks, id) {
    let i;
    for (i = 0; i < tracks.length; i++) {
      if (tracks[i].id === id) {
        return tracks[i];
      }
    }

    return undefined;
  };

  static instrumentByID(instruments, id) {
    let i;
    for (i = 0; i < instruments.length; i++) {
      if (instruments[i].id === id) {
        return instruments[i];
      }
    }

    return undefined;
  };

  static patternsByTrackID(allPatterns, trackID) {
    let i;
    let patterns = [];

    for (i = 0; i < allPatterns.length; i++) {
      if (allPatterns[i].trackID === trackID) {
        patterns.push(allPatterns[i]);
      }
    }

    return patterns;
  };

  static serialize(tracks, instruments, patterns) {
    let i, j;
    let serializedInstrument;
    let serializedPatterns;
    let serializedNotes = [];

    for (i = 0; i < (8 * 16); i++) {
      serializedNotes[i] = [];
    }

    let trackVolumeMultiplier = 1 / tracks.length;

    tracks.forEach(function(track) {
      if (track.muted) {
        return;
      }

      serializedInstrument = Serializer.serializeInstrument(Serializer.instrumentByID(instruments, track.instrumentID));
      serializedPatterns = Serializer.serializePatterns(Serializer.patternsByTrackID(patterns, track.id));

      for (i = 0; i < track.patterns.length; i++) {
        if (track.patterns[i].patternID !== -1) {
          let sequences = serializedPatterns[track.patterns[i].patternID];

          sequences.forEach(function(sequence) {
            for (j = 0; j < sequence.length; j++) {
              if (sequence[j] && sequence[j].name()) {
                serializedNotes[(i * 16) + j].push(new JSSynth.InstrumentNote(sequence[j], serializedInstrument, track.volume * trackVolumeMultiplier));
              }
            }
          });
        }
      }
    });

    return serializedNotes;
  };
};

export { Serializer };
<commit_msg>Extracting constants<commit_after>"use strict";

import * as JSSynth from "./jssynth";

class Serializer {
  constructor() {};

  static serializeInstrument(instrument) {
    let filterCutoff = parseInt(instrument.filterCutoff, 10);

    let serializedConfig = {
      oscillators: [
        {
          waveform: instrument.waveform1,
          octave: parseInt(instrument.waveform1Octave),
          detune: 0,
        },
        {
          waveform: instrument.waveform2,
          octave: parseInt(instrument.waveform2Octave),
          detune: parseInt(instrument.waveform2Detune),
        }
      ],
      lfo: {
        waveform:  instrument.lfoWaveform,
        frequency: parseFloat(instrument.lfoFrequency),
        amplitude: parseInt(instrument.lfoAmplitude, 10),
      },
      filter: {
        cutoff:    filterCutoff,
        resonance: parseInt(instrument.filterResonance, 10),
        mode: instrument.filterModulator,
        lfo: {
          waveform:  instrument.filterLFOWaveform,
          frequency: parseFloat(instrument.filterLFOFrequency),
          amplitude: parseFloat(instrument.filterLFOAmplitude) * filterCutoff,
        },
        envelope: {
          attack:  parseFloat(instrument.filterEnvelopeAttack),
          decay:   parseFloat(instrument.filterEnvelopeDecay),
          sustain: parseFloat(instrument.filterEnvelopeSustain),
          release: parseFloat(instrument.filterEnvelopeRelease),
        },
      },
      envelope: {
        attack:  parseFloat(instrument.envelopeAttack),
        decay:   parseFloat(instrument.envelopeDecay),
        sustain: parseFloat(instrument.envelopeSustain),
        release: parseFloat(instrument.envelopeRelease),
      },
    };

    return new JSSynth.Instrument(serializedConfig);
  };

  static serializePatterns(patterns) {
    let serializedPatterns = {};

    patterns.forEach(function(pattern) {
      let serializedRows = [];

      pattern.rows.forEach(function(row) {
        let sequence;
        let rawSequenceString;

        rawSequenceString = row.notes.map(function(note) { return note.name; }).join(' ');
        sequence = JSSynth.SequenceParser.parse(rawSequenceString);
        serializedRows.push(sequence);
      });

      serializedPatterns[pattern.id] = serializedRows;
    });

    return serializedPatterns;
  };

  static trackByID(tracks, id) {
    let i;
    for (i = 0; i < tracks.length; i++) {
      if (tracks[i].id === id) {
        return tracks[i];
      }
    }

    return undefined;
  };

  static instrumentByID(instruments, id) {
    let i;
    for (i = 0; i < instruments.length; i++) {
      if (instruments[i].id === id) {
        return instruments[i];
      }
    }

    return undefined;
  };

  static patternsByTrackID(allPatterns, trackID) {
    let i;
    let patterns = [];

    for (i = 0; i < allPatterns.length; i++) {
      if (allPatterns[i].trackID === trackID) {
        patterns.push(allPatterns[i]);
      }
    }

    return patterns;
  };

  static serialize(tracks, instruments, patterns) {
    const MEASURES = 8;
    const STEPS_PER_MEASURE = 16;
    const TOTAL_STEPS = MEASURES * STEPS_PER_MEASURE;

    let i, j;
    let serializedInstrument;
    let serializedPatterns;
    let serializedNotes = [];

    for (i = 0; i < TOTAL_STEPS; i++) {
      serializedNotes[i] = [];
    }

    let trackVolumeMultiplier = 1 / tracks.length;

    tracks.forEach(function(track) {
      if (track.muted) {
        return;
      }

      serializedInstrument = Serializer.serializeInstrument(Serializer.instrumentByID(instruments, track.instrumentID));
      serializedPatterns = Serializer.serializePatterns(Serializer.patternsByTrackID(patterns, track.id));

      for (i = 0; i < track.patterns.length; i++) {
        if (track.patterns[i].patternID !== -1) {
          let sequences = serializedPatterns[track.patterns[i].patternID];

          sequences.forEach(function(sequence) {
            for (j = 0; j < sequence.length; j++) {
              if (sequence[j] && sequence[j].name()) {
                serializedNotes[(i * STEPS_PER_MEASURE) + j].push(new JSSynth.InstrumentNote(sequence[j], serializedInstrument, track.volume * trackVolumeMultiplier));
              }
            }
          });
        }
      }
    });

    return serializedNotes;
  };
};

export { Serializer };
<|endoftext|>


<commit_before><commit_msg>updates<commit_after><|endoftext|>


<commit_before>/* NODE MODULES */
var zoneElements = require('../elements'),
    zoneQuadrants = require('../quadrants');

/** MODULE INTERFACE
 *@method {function} define - Define the properties of a zone and attach event emitters monitor their changes
 */
module.exports = {
    define: define
};

/*----------------------------------------------------------------------------*/

/** Define the properties of a zone and attach event emitters monitor their changes
 * @param
 * @returns
 */
function define(properties, globalNamespace, localNamespace) {
    var propertiesEvents = localNamespace.emitter();
    function createZoneProperties() {
        var zoneProperties = {
            // ID of the zone
            id: {
                value: properties.id
            },
            // Name of the zone
            name: changeGetterSetter('name', 'name', properties.name),
            // Size of the zone
            size: {
                value: Object.create({}, {
                    x: changeGetterSetter('size', 'x', properties.size.x),
                    y: changeGetterSetter('size', 'y', properties.size.y),
                    z: changeGetterSetter('size', 'z', properties.size.z)
                })
            },
            // Zone limits
            limits: marginGetterSetter('limits', properties.limits),
            // Zone center coordinates
            coordinates: {
                value: Object.create({}, {
                    x: changeGetterSetter('coordinates', 'x', properties.coordinates.x),
                    y: changeGetterSetter('coordinates', 'y', properties.coordinates.y),
                    z: changeGetterSetter('coordinates', 'z', properties.coordinates.z)
                })
            },
            // Maximum range of visibility
            visibility: {
                value: Object.create({}, {
                    horizontal: changeGetterSetter('visibility', 'horizontal', properties.visibility.horizontal),
                    vertical: changeGetterSetter('visibility', 'vertical', properties.visibility.vertical)
                })
            },
            // Bookin and checkin margin size
            handover: changeGetterSetter('handover', 'handover', properties.handover),
            // Zone scope and handover limits
            margins: {
                value: Object.create({}, {
                    scope: {
                        value: Object.create({}, {
                            inner: marginGetterSetter('innerScope', properties.margins.scope.inner),
                            outer: marginGetterSetter('outerScope', properties.margins.scope.outer)
                        })
                    },
                    handover: {
                        value: Object.create({}, {
                            bookin: marginGetterSetter('bookinMargin', properties.margins.handover.bookin),
                            checkin: marginGetterSetter('checkinMargin', properties.margins.handover.checkin)
                        })
                    }
                })
            },
            elements: zoneElements.createContainer(localNamespace.emitter())
        };

        zoneProperties.quadrants = {
            value: zoneQuadrants.create(globalNamespace, localNamespace.emitter(), zoneProperties.margins.value)
        };

        return zoneProperties;
    }

    /*----------------------------------------------------------------------------*/

    function changeGetterSetter(typeofChange, propertyChanged, initialValue) {
        var value = initialValue;
        return {
            get: function () {
                return value;
            },
            set: function (newValue) {
                value = newValue;
                propertiesEvents.emit(typeofChange + 'Change', {
                    property: propertyChanged,
                    value: newValue
                });
            }
        }
    }

    function marginGetterSetter(typeofChange, margins) {
        function margin(propertyChanged, margin) {
            return {
                value: Object.create({}, {
                    lower: (function (value) {
                        return {
                            get: function () {
                                return value;
                            },
                            set: function (newValue) {
                                // value = newValue;
                                propertiesEvents.emit(typeofChange + 'Change', {
                                    property: propertyChanged,
                                    side: 'lower',
                                    value: newValue
                                });
                            }
                        };
                    })(margin.lower),
                    higher: (function (value) {
                        return {
                            get: function () {
                                return value;
                            },
                            set: function (newValue) {
                                // value = newValue;
                                propertiesEvents.emit(typeofChange + 'Change', {
                                    property: propertyChanged,
                                    side: 'higher',
                                    value: newValue
                                });
                            }
                        };
                    })(margin.higher)
                })
            };
        }
        return {
            value: Object.create({}, {
                x: margin('x', margins.x),
                y: margin('y', margins.y),
                z: margin('z', margins.z)
            })
        }
    }

    /*----------------------------------------------------------------------------*/

    return createZoneProperties();
}<commit_msg>Moved the definition of the 'elements' property after the 'quadrants' property<commit_after>/* NODE MODULES */
var zoneElements = require('../elements'),
    zoneQuadrants = require('../quadrants');

/** MODULE INTERFACE
 *@method {function} define - Define the properties of a zone and attach event emitters monitor their changes
 */
module.exports = {
    define: define
};

/*----------------------------------------------------------------------------*/

/** Define the properties of a zone and attach event emitters monitor their changes
 * @param
 * @returns
 */
function define(properties, globalNamespace, localNamespace) {
    var propertiesEvents = localNamespace.emitter();

    return (function createZoneProperties() {
        var zoneProperties = {
            // ID of the zone
            id: {
                value: properties.id
            },
            // Name of the zone
            name: changeGetterSetter('name', 'name', properties.name),
            // Size of the zone
            size: {
                value: Object.create({}, {
                    x: changeGetterSetter('size', 'x', properties.size.x),
                    y: changeGetterSetter('size', 'y', properties.size.y),
                    z: changeGetterSetter('size', 'z', properties.size.z)
                })
            },
            // Zone limits
            limits: marginGetterSetter('limits', properties.limits),
            // Zone center coordinates
            coordinates: {
                value: Object.create({}, {
                    x: changeGetterSetter('coordinates', 'x', properties.coordinates.x),
                    y: changeGetterSetter('coordinates', 'y', properties.coordinates.y),
                    z: changeGetterSetter('coordinates', 'z', properties.coordinates.z)
                })
            },
            // Maximum range of visibility
            visibility: {
                value: Object.create({}, {
                    horizontal: changeGetterSetter('visibility', 'horizontal', properties.visibility.horizontal),
                    vertical: changeGetterSetter('visibility', 'vertical', properties.visibility.vertical)
                })
            },
            // Bookin and checkin margin size
            handover: changeGetterSetter('handover', 'handover', properties.handover),
            // Zone scope and handover limits
            margins: {
                value: Object.create({}, {
                    scope: {
                        value: Object.create({}, {
                            inner: marginGetterSetter('innerScope', properties.margins.scope.inner),
                            outer: marginGetterSetter('outerScope', properties.margins.scope.outer)
                        })
                    },
                    handover: {
                        value: Object.create({}, {
                            bookin: marginGetterSetter('bookinMargin', properties.margins.handover.bookin),
                            checkin: marginGetterSetter('checkinMargin', properties.margins.handover.checkin)
                        })
                    }
                })
            }
        };

        var quadrants = zoneQuadrants.create(globalNamespace, localNamespace.emitter(), zoneProperties.margins.value);
        zoneProperties.quadrants = {
            value: quadrants
        };

        zoneProperties.elements = zoneElements.createContainer(localNamespace.emitter(), quadrants);

        return zoneProperties;
    })();

    /*----------------------------------------------------------------------------*/

    function changeGetterSetter(typeofChange, propertyChanged, initialValue) {
        var value = initialValue;
        return {
            get: function () {
                return value;
            },
            set: function (newValue) {
                value = newValue;
                propertiesEvents.emit(typeofChange + 'Change', {
                    property: propertyChanged,
                    value: newValue
                });
            }
        }
    }

    function marginGetterSetter(typeofChange, margins) {
        function margin(propertyChanged, margin) {
            return {
                value: Object.create({}, {
                    lower: (function (value) {
                        return {
                            get: function () {
                                return value;
                            },
                            set: function (newValue) {
                                // value = newValue;
                                propertiesEvents.emit(typeofChange + 'Change', {
                                    property: propertyChanged,
                                    side: 'lower',
                                    value: newValue
                                });
                            }
                        };
                    })(margin.lower),
                    higher: (function (value) {
                        return {
                            get: function () {
                                return value;
                            },
                            set: function (newValue) {
                                // value = newValue;
                                propertiesEvents.emit(typeofChange + 'Change', {
                                    property: propertyChanged,
                                    side: 'higher',
                                    value: newValue
                                });
                            }
                        };
                    })(margin.higher)
                })
            };
        }
        return {
            value: Object.create({}, {
                x: margin('x', margins.x),
                y: margin('y', margins.y),
                z: margin('z', margins.z)
            })
        }
    }

    /*----------------------------------------------------------------------------*/
}<|endoftext|>


<commit_before>import vertex from './zoom-blur.vert';
import fragment from './zoom-blur.frag';

/**
 * The ZoomFilter applies a Zoom blur to an object.
 * ![original](../tools/screenshots/dist/original.png)![filter](../tools/screenshots/dist/zoom-blur.png)
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 * @param {number} [strength=2] Sets the strength of the zoom blur effect
 * @param {PIXI.Point|number[]} [center=[0,0]] The center of the zoom.
 * @param {number} [innerRadius=0] The inner radius of zoom. The part in inner circle won't apply zoom blur effect.
 * @param {number} [radius=1E8] Outer radius of the zoom, The default value is very very large.
 */
export default class ZoomBlurFilter extends PIXI.Filter
{
    constructor(strength = 0.1, center = [0, 0], innerRadius = 0, radius = 1E8) {
        super(vertex, fragment);

        this.center = center;
        this.strength = strength;
        this.innerRadius = innerRadius;
        this.radius = radius;
    }

    /**
     * Center of the effect.
     *
     * @member {PIXI.Point|number[]}
     * @default [0, 0]
     */
    get center() {
        return this.uniforms.uCenter;
    }
    set center(value) {
        this.uniforms.uCenter = value;
    }

    /**
     * Intensity of the zoom effect.
     *
     * @member {number}
     * @default 0.1
     */
    get strength() {
        return this.uniforms.uStrength;
    }
    set strength(value) {
        this.uniforms.uStrength = value;
    }

    /**
     * Radius of the inner region not effected by blur.
     *
     * @member {number}
     * @default 0
     */
    get innerRadius() {
        return this.uniforms.uInnerRadius;
    }
    set innerRadius(value) {
        this.uniforms.uInnerRadius = value;
    }

    /**
     * Outer radius of the effect. The default value is very very big.
     *
     * @member {number}
     * @default 1E9
     */
    get radius() {
        return this.uniforms.uRadius;
    }
    set radius(value) {
        this.uniforms.uRadius = value;
    }
}

// Export to PixiJS namespace
PIXI.filters.ZoomBlurFilter = ZoomBlurFilter;

<commit_msg>Fix documentation<commit_after>import vertex from './zoom-blur.vert';
import fragment from './zoom-blur.frag';

/**
 * The ZoomFilter applies a Zoom blur to an object.
 * ![original](../tools/screenshots/dist/original.png)![filter](../tools/screenshots/dist/zoom-blur.png)
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 * @param {number} [strength=0.1] Sets the strength of the zoom blur effect
 * @param {PIXI.Point|number[]} [center=[0,0]] The center of the zoom.
 * @param {number} [innerRadius=0] The inner radius of zoom. The part in inner circle won't apply zoom blur effect.
 * @param {number} [radius=1E8] Outer radius of the zoom, The default value is very very large.
 */
export default class ZoomBlurFilter extends PIXI.Filter
{
    constructor(strength = 0.1, center = [0, 0], innerRadius = 0, radius = 1E8) {
        super(vertex, fragment);

        this.center = center;
        this.strength = strength;
        this.innerRadius = innerRadius;
        this.radius = radius;
    }

    /**
     * Center of the effect.
     *
     * @member {PIXI.Point|number[]}
     * @default [0, 0]
     */
    get center() {
        return this.uniforms.uCenter;
    }
    set center(value) {
        this.uniforms.uCenter = value;
    }

    /**
     * Intensity of the zoom effect.
     *
     * @member {number}
     * @default 0.1
     */
    get strength() {
        return this.uniforms.uStrength;
    }
    set strength(value) {
        this.uniforms.uStrength = value;
    }

    /**
     * Radius of the inner region not effected by blur.
     *
     * @member {number}
     * @default 0
     */
    get innerRadius() {
        return this.uniforms.uInnerRadius;
    }
    set innerRadius(value) {
        this.uniforms.uInnerRadius = value;
    }

    /**
     * Outer radius of the effect. The default value is very very big.
     *
     * @member {number}
     * @default 1E8
     */
    get radius() {
        return this.uniforms.uRadius;
    }
    set radius(value) {
        this.uniforms.uRadius = value;
    }
}

// Export to PixiJS namespace
PIXI.filters.ZoomBlurFilter = ZoomBlurFilter;

<|endoftext|>


<commit_before>/* browserify task
   ---------------
   Bundle javascripty things with browserify!

   This task is set up to generate multiple separate bundles, from different
   sources, and to use Watchify when run from the default task.

   See browserify.bundleConfigs in gulp/config.js
*/

var browserify = require('browserify');
var bundleLogger = require('../util/bundleLogger');
var exorcist = require('exorcist');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var to5ify = require('6to5ify');
var watchify = require('watchify');
var config = require('../config').browserify;

gulp.task('browserify', function(callback) {
	var bundleQueue = config.bundleConfigs.length;

	var browserifyThis = function(bundleConfig) {
		var bundler = browserify({
			// Required watchify args
			cache: {}, packageCache: {}, fullPaths: true,
			// Specify the entry point of your app
			entries: bundleConfig.entries,
			// Add file extentions to make optional in your requires
			extensions: config.extensions,
			// Enable source maps!
			debug: config.debug,
		});

		bundler.transform(to5ify.configure({
			blacklist: ['generators'],
		}));

		var bundle = function() {
			// Log when bundling starts
			bundleLogger.start(bundleConfig.outputName);

			return bundler
				.bundle()
				// Report compile errors
				.on('error', handleErrors)
				// Use exorcist to remove the map file
				.pipe(exorcist(bundleConfig.mapFile))
				// Use vinyl-source-stream to make the stream gulp compatible.
				// Specifiy the desired output filename here.
				.pipe(source(bundleConfig.outputName))
				// Specify the output destination
				.pipe(gulp.dest(bundleConfig.dest))
				.on('end', reportFinished);
		};

		if (global.isWatching) {
			// Wrap with watchify and rebundle on changes
			bundler = watchify(bundler);
			// Rebundle on update
			bundler.on('update', bundle);
		}

		var reportFinished = function() {
			// Log when bundling completes
			bundleLogger.end(bundleConfig.outputName)

			if (bundleQueue) {
				bundleQueue--;
				if (bundleQueue === 0) {
					// If queue is empty, tell gulp the task is complete.
					// https://github.com/gulpjs/gulp/blob/master/docs/API.md#accept-a-callback
					callback();
				}
			}
		};

		return bundle();
	};

	// Start bundling with Browserify for each bundleConfig specified
	config.bundleConfigs.forEach(browserifyThis);
});
<commit_msg>Use `mold` to make the sourcemps relative<commit_after>/* browserify task
   ---------------
   Bundle javascripty things with browserify!

   This task is set up to generate multiple separate bundles, from different
   sources, and to use Watchify when run from the default task.

   See browserify.bundleConfigs in gulp/config.js
*/

var browserify = require('browserify');
var bundleLogger = require('../util/bundleLogger');
var exorcist = require('exorcist');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var mold = require('mold-source-map');
var source = require('vinyl-source-stream');
var to5ify = require('6to5ify');
var watchify = require('watchify');
var config = require('../config').browserify;

gulp.task('browserify', function(callback) {
	var bundleQueue = config.bundleConfigs.length;

	var browserifyThis = function(bundleConfig) {
		var bundler = browserify({
			// Required watchify args
			cache: {}, packageCache: {}, fullPaths: true,
			// Specify the entry point of your app
			entries: bundleConfig.entries,
			// Add file extentions to make optional in your requires
			extensions: config.extensions,
			// Enable source maps!
			debug: config.debug,
		});

		bundler.transform(to5ify.configure({
			blacklist: ['generators'],
		}));

		var bundle = function() {
			// Log when bundling starts
			bundleLogger.start(bundleConfig.outputName);

			return bundler
				.bundle()
				// Report compile errors
				.on('error', handleErrors)
				// Make the sourcemap relative
				.pipe(mold.transformSourcesRelativeTo('.'))
				// Use exorcist to remove the map file
				.pipe(exorcist(bundleConfig.mapFile))
				// Use vinyl-source-stream to make the stream gulp compatible.
				// Specifiy the desired output filename here.
				.pipe(source(bundleConfig.outputName))
				// Specify the output destination
				.pipe(gulp.dest(bundleConfig.dest))
				.on('end', reportFinished);
		};

		if (global.isWatching) {
			// Wrap with watchify and rebundle on changes
			bundler = watchify(bundler);
			// Rebundle on update
			bundler.on('update', bundle);
		}

		var reportFinished = function() {
			// Log when bundling completes
			bundleLogger.end(bundleConfig.outputName)

			if (bundleQueue) {
				bundleQueue--;
				if (bundleQueue === 0) {
					// If queue is empty, tell gulp the task is complete.
					// https://github.com/gulpjs/gulp/blob/master/docs/API.md#accept-a-callback
					callback();
				}
			}
		};

		return bundle();
	};

	// Start bundling with Browserify for each bundleConfig specified
	config.bundleConfigs.forEach(browserifyThis);
});
<|endoftext|>