<commit_before>/*global $j, loadingDialogInstance, psData*/

$j(function () {
    'use strict';
    var config = {
        // PowerSchool Point of Contact server, which will talk with the PS REST API.
        "psPoc": "https://psapi.irondistrict.org",

        // Student Contacts Database Extension Table Name
        "stuInfoStagingDbe": "u_student_info_staging"
    };

    // Populate student email address on page load
    $j.get('/admin/students/brij_renderform.html?frn=001' + psData.studentFrn, function (studentEmailHtml) {
        $j.get('/admin/students/studentinfochange.html?frn=001' + psData.studentDcid, function() {
            var parsedHtml = $j.parseHTML(studentEmailHtml);
            var $html = $j(parsedHtml);
            var studentEmailValue = $html.find('#studEmail_0').val();
            $j('#on-file-student-email').val(studentEmailValue);

            loadingDialogInstance.open();

            var studentInInfoStaging;
            $j.get(config.psPoc + '/dbe/schema/search/u_def_ext_students/studentsdcid==' + psData.studentDcid, function (resp) {

                // Check if student has staging record
                studentInInfoStaging = resp.record.length !== 0;

                if (psData.parent_verify.trim() === "1") {
                    $j('#parent-verify').attr('checked', 'checked');
                }

                if (studentInInfoStaging) {
                    $j('#staging-on-file').css({'display': 'block'});
                    loadStagingData();
                } else if (psData.parent_verify === "1") {
                    $j('.linkDescList').css({'display': 'none'});
                    var template = $j('#parent-verify-msg-template').html();
                    var insertSelector = $j('table').eq(0);
                    $j(template).insertAfter(insertSelector);
                    loadingDialogInstance.forceClose();
                } else {
                    $j('.linkDescList').css({'display': 'none'});
                    $j('#uncheck-span').css({'display': 'none'});
                    $j('#parent-verify').css({'display': 'none'});
                    loadingDialogInstance.forceClose();
                }

                // Load staging data into form.
                function loadStagingData() {
                    $j.get(config.psPoc + '/dbe/schema/search/u_def_ext_students/studentsdcid==' + psData.studentDcid, function (resp) {
                        loadingDialogInstance.forceClose();

                        var studentInfo = resp.record[0].tables[config.stuInfoStagingDbe];
                        $j('#staging-mailing-street').val(studentInfo.mailing_street);
                        $j('#staging-mailing-city').val(studentInfo.mailing_city);
                        $j('#staging-mailing-state').val(studentInfo.mailing_state);
                        $j('#staging-mailing-zip').val(studentInfo.mailing_zip);

                        $j('#staging-residence-street').val(studentInfo.residence_street);
                        $j('#staging-residence-city').val(studentInfo.residence_city);
                        $j('#staging-residence-state').val(studentInfo.residence_state);
                        $j('#staging-residence-zip').val(studentInfo.residence_zip);

                        $j('#staging-student-email').val(studentInfo.student_email);
                        $j('#staging-student-cell-phone').val(studentInfo.student_cell_phone);
                        $j('#staging-dentist-name').val(studentInfo.dentist_name);
                        $j('#staging-dentist-phone').val(studentInfo.dentist_phone);
                        $j('#staging-doctor-name').val(studentInfo.doctor_name);
                        $j('#staging-doctor-phone').val(studentInfo.doctor_phone);
                    }, 'json');
                }

                /**
                 * @returns {Boolean} - true if all staging fields are empty, false if not empty.
                 */
                function stagingFormIsEmpty() {
                    var isEmpty = true;
                    if ($j('#staging-mailing-street').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-mailing-city').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-mailing-state').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-mailing-zip').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-street').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-city').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-state').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-zip').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-student-email').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-student-cell-phone').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-dentist-name').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-dentist-phone').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-doctor-name').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-doctor-phone').val()) {
                        isEmpty = false;
                    }
                    return isEmpty;
                }

                // Save student email before the rest of the form submits
                $j('#approve-dentist-name').on('click', function (event) {
                    var fieldName = $j('#on-file-dentist-name').attr('name');
                    approveFieldChange(fieldName, 'staging-dentist-name');
                });
                $j('#approve-dentist-phone').on('click', function (event) {
                    var fieldName = $j('#on-file-dentist-phone').attr('name');
                    approveFieldChange(fieldName, 'staging-dentist-phone');
                });

                if (stagingFormIsEmpty() && studentInInfoStaging) {
                    $j('#student-info-form').one('submit', function (event) {
                        event.preventDefault();

                        $j('.staging').attr({'disabled': 'disabled'});
                        var deleteFieldName = 'DC-Students:' + psData.studentDcid + '.U_STUDENT_INFO.U_STUDENT_INFO_STAGING:' + psData.studentInfoStagingId;
                        var deleteData = {
                            'ac': 'prim'
                        };
                        deleteData[deleteFieldName] = 'on';
                        $j.ajax({
                            type: "POST",
                            data: deleteData,
                            async: false,
                            url: "/admin/changesrecorded.white.html"
                        }).done(function () {
                            var postData = {
                                'userSentContact.email': $j('#on-file-student-email').val(),
                                'userSentContact.id': psData.psmStudentContactId,
                                'userSentContact.studentID': psData.psmStudentId,
                                'userSentContact.studentContactTypeID': psData.psmStudentContactTypeId,
                                'deleteFlag_0': 'deleteFlag_0',
                                'ac': 'brij:studentemail/StoreStudentEmails',
                                'doc': '/admin/students/emailconfig.html',
                                'render_in_java': 'true',
                                'frn': psData.studentFrn
                            };

                            $j.ajax({
                                type: "POST",
                                data: postData,
                                async: false,
                                url: "/admin/students/emailconfig.html"
                            }).done(function (resp) {
                                $j.get('/admin/students/studentinfochange.html', function() {
                                    return true;
                                });
                            });
                        });
                    });
                }
            }, 'json');
        });
    });
});<commit_msg>Fixed psPoc api calls in student-info.js<commit_after>/*global $j, loadingDialogInstance, psData*/

$j(function () {
    'use strict';
    var config = {
        // PowerSchool Point of Contact server, which will talk with the PS REST API.
        "psPoc": "https://psapi.irondistrict.org",

        // Student Contacts Database Extension Table Name
        "stuInfoStagingDbe": "u_student_info_staging"
    };

    // Populate student email address on page load
    $j.get('/admin/students/brij_renderform.html?frn=001' + psData.studentFrn, function (studentEmailHtml) {
        $j.get('/admin/students/studentinfochange.html?frn=001' + psData.studentDcid, function() {
            var parsedHtml = $j.parseHTML(studentEmailHtml);
            var $html = $j(parsedHtml);
            var studentEmailValue = $html.find('#studEmail_0').val();
            $j('#on-file-student-email').val(studentEmailValue);

            loadingDialogInstance.open();

            var studentInInfoStaging;
            $j.get(config.psPoc + '/dbe/schema/search/u_def_ext_students/studentsdcid==' + psData.studentDcid + '&student_info_verify==1', function (resp) {

                // Check if student has staging record
                studentInInfoStaging = resp.record.length !== 0;

                if (psData.parent_verify.trim() === "1") {
                    $j('#parent-verify').attr('checked', 'checked');
                }

                if (studentInInfoStaging) {
                    $j('#staging-on-file').css({'display': 'block'});
                    loadStagingData();
                } else if (psData.parent_verify === "1") {
                    $j('.linkDescList').css({'display': 'none'});
                    var template = $j('#parent-verify-msg-template').html();
                    var insertSelector = $j('table').eq(0);
                    $j(template).insertAfter(insertSelector);
                    loadingDialogInstance.forceClose();
                } else {
                    $j('.linkDescList').css({'display': 'none'});
                    $j('#uncheck-span').css({'display': 'none'});
                    $j('#parent-verify').css({'display': 'none'});
                    loadingDialogInstance.forceClose();
                }

                // Load staging data into form.
                function loadStagingData() {
                    $j.get(config.psPoc + '/dbe/schema/search/' + config.stuInfoStagingDbe + '/studentsdcid==' + psData.studentDcid, function (resp) {
                        loadingDialogInstance.forceClose();

                        var studentInfo = resp.record[0].tables[config.stuInfoStagingDbe];
                        $j('#staging-mailing-street').val(studentInfo.mailing_street);
                        $j('#staging-mailing-city').val(studentInfo.mailing_city);
                        $j('#staging-mailing-state').val(studentInfo.mailing_state);
                        $j('#staging-mailing-zip').val(studentInfo.mailing_zip);

                        $j('#staging-residence-street').val(studentInfo.residence_street);
                        $j('#staging-residence-city').val(studentInfo.residence_city);
                        $j('#staging-residence-state').val(studentInfo.residence_state);
                        $j('#staging-residence-zip').val(studentInfo.residence_zip);

                        $j('#staging-student-email').val(studentInfo.student_email);
                        $j('#staging-student-cell-phone').val(studentInfo.student_cell_phone);
                        $j('#staging-dentist-name').val(studentInfo.dentist_name);
                        $j('#staging-dentist-phone').val(studentInfo.dentist_phone);
                        $j('#staging-doctor-name').val(studentInfo.doctor_name);
                        $j('#staging-doctor-phone').val(studentInfo.doctor_phone);
                    }, 'json');
                }

                /**
                 * @returns {Boolean} - true if all staging fields are empty, false if not empty.
                 */
                function stagingFormIsEmpty() {
                    var isEmpty = true;
                    if ($j('#staging-mailing-street').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-mailing-city').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-mailing-state').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-mailing-zip').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-street').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-city').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-state').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-residence-zip').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-student-email').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-student-cell-phone').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-dentist-name').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-dentist-phone').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-doctor-name').val()) {
                        isEmpty = false;
                    }
                    if ($j('#staging-doctor-phone').val()) {
                        isEmpty = false;
                    }
                    return isEmpty;
                }

                // Save student email before the rest of the form submits
                $j('#approve-dentist-name').on('click', function (event) {
                    var fieldName = $j('#on-file-dentist-name').attr('name');
                    approveFieldChange(fieldName, 'staging-dentist-name');
                });
                $j('#approve-dentist-phone').on('click', function (event) {
                    var fieldName = $j('#on-file-dentist-phone').attr('name');
                    approveFieldChange(fieldName, 'staging-dentist-phone');
                });

                if (stagingFormIsEmpty() && studentInInfoStaging) {
                    $j('#student-info-form').one('submit', function (event) {
                        event.preventDefault();

                        $j('.staging').attr({'disabled': 'disabled'});
                        var deleteFieldName = 'DC-Students:' + psData.studentDcid + '.U_STUDENT_INFO.U_STUDENT_INFO_STAGING:' + psData.studentInfoStagingId;
                        var deleteData = {
                            'ac': 'prim'
                        };
                        deleteData[deleteFieldName] = 'on';
                        $j.ajax({
                            type: "POST",
                            data: deleteData,
                            async: false,
                            url: "/admin/changesrecorded.white.html"
                        }).done(function () {
                            var postData = {
                                'userSentContact.email': $j('#on-file-student-email').val(),
                                'userSentContact.id': psData.psmStudentContactId,
                                'userSentContact.studentID': psData.psmStudentId,
                                'userSentContact.studentContactTypeID': psData.psmStudentContactTypeId,
                                'deleteFlag_0': 'deleteFlag_0',
                                'ac': 'brij:studentemail/StoreStudentEmails',
                                'doc': '/admin/students/emailconfig.html',
                                'render_in_java': 'true',
                                'frn': psData.studentFrn
                            };

                            $j.ajax({
                                type: "POST",
                                data: postData,
                                async: false,
                                url: "/admin/students/emailconfig.html"
                            }).done(function (resp) {
                                $j.get('/admin/students/studentinfochange.html', function() {
                                    return true;
                                });
                            });
                        });
                    });
                }
            }, 'json');
        });
    });
});<|endoftext|>


<commit_before>"use strict";

var fs = require( "fs" );
var GlobalizeCompilerPlus = require( "../index" ).compile;
var nopt = require( "nopt" );
var path = require( "path" );
var pkg = require( "../package.json" );
var mkdirp = require('mkdirp');

function help() {
  var out = [
    "Usage: globalize-compiler-plus [-l LOCALES] -m MESSAGES_FILE -o DEST_DIR -a APP_ROOT SRC_FILES",
    "Example: globalize-compiler-plus -l en,fr,es,de -m test/messages.json -a output/-o test/output/ test/*.js",
    "",
    " Default Locales used are those provided in messages.json file",
    "",
    "General options:",
    "  -h, --help                     # Print options and usage.",
    "  -v, --version                  # Print the version number.",
    "  -l, --locales                  # Optional.  Comma separated list of specific locale(s) to override those in messages.json",
    "  -m, --messages MESSAGES_FILE   # Translation messages for internal locales (JSON format).",
    "  -o, --output DEST_DIR          # Outputs files of the form formatters-<locale>.js",
    "  -a, --approot PATH             # For web helpers, the runtime, client side path to the directories the formatters will live.  See webpack-helper.js output for more",
    ""
  ];

  return out.join( "\n" );
}

var opts = nopt( {
  help: Boolean,
  version: Boolean,
  locales: String,
  messages: path,
  output: path,
  approot : String
}, {
  h: "--help",
  v: "--version",
  l: "--locales",
  m: "--messages",
  o: "--output",
  a: "--approot"
});
var requiredOpts = true;

if ( opts.version ) {
  return console.log( pkg.version );
}

if ( !opts.approot || !opts.messages || !opts.output ) {
  requiredOpts = false;
}

var extraOptions = Object.keys( opts ).filter(function( option ) {
  return !/help|version|locale|approot|cldr|messages|output|argv/.test( option );
});

if ( extraOptions.length ) {
  console.log( "Invalid options:", extraOptions.join( ", " ), "\n" );
}

if ( opts.help || !requiredOpts || extraOptions.length ) {
  return console.log( help() );
}

var input = opts.argv.remain;
var messages = opts.messages;
var output = opts.output;
var approot = opts.approot

var messages = messages ? JSON.parse( fs.readFileSync( messages ) ) : null;

// preferred to get locales from those defined in messages file
if(!opts.locales){
  locales = Object.keys(messages)
} else {
  var locales = opts.locales.split(',');
}

var filesObj = GlobalizeCompilerPlus(input, messages, locales, approot)
var bundleObj = filesObj.formatters

mkdirp(output)

// write helpers
var filenames = Object.keys(filesObj)
for (var f in filenames){
  var filename = filenames[f]
  if(filename == "formatters"){
    continue
  }
  var filepath = path.join(output, filename)
  fs.writeFileSync(filepath, filesObj[filename])
}

locales = Object.keys(bundleObj)
for (var i in locales){
  var locale = locales[i]
  if(locale == "root"){
    continue
  }
  var filename = path.join(output, "formatters-" + locale + ".js")
  var bundle = bundleObj[locale]
  fs.writeFileSync(filename, bundle);
}
<commit_msg>Make helper file paths compatible with windows<commit_after>"use strict";

var fs = require( "fs" );
var GlobalizeCompilerPlus = require( "../index" ).compile;
var nopt = require( "nopt" );
var path = require( "path" );
var pkg = require( "../package.json" );
var mkdirp = require('mkdirp');

function help() {
  var out = [
    "Usage: globalize-compiler-plus [-l LOCALES] -m MESSAGES_FILE -o DEST_DIR -a APP_ROOT SRC_FILES",
    "Example: globalize-compiler-plus -l en,fr,es,de -m test/messages.json -a output/-o test/output/ test/*.js",
    "",
    " Default Locales used are those provided in messages.json file",
    "",
    "General options:",
    "  -h, --help                     # Print options and usage.",
    "  -v, --version                  # Print the version number.",
    "  -l, --locales                  # Optional.  Comma separated list of specific locale(s) to override those in messages.json",
    "  -m, --messages MESSAGES_FILE   # Translation messages for internal locales (JSON format).",
    "  -o, --output DEST_DIR          # Outputs files of the form formatters-<locale>.js",
    "  -a, --approot PATH             # For web helpers, the runtime, client side path to the directories the formatters will live.  See webpack-helper.js output for more",
    ""
  ];

  return out.join( "\n" );
}

var opts = nopt( {
  help: Boolean,
  version: Boolean,
  locales: String,
  messages: path,
  output: path,
  approot : String
}, {
  h: "--help",
  v: "--version",
  l: "--locales",
  m: "--messages",
  o: "--output",
  a: "--approot"
});
var requiredOpts = true;

if ( opts.version ) {
  return console.log( pkg.version );
}

if ( !opts.approot || !opts.messages || !opts.output ) {
  requiredOpts = false;
}

var extraOptions = Object.keys( opts ).filter(function( option ) {
  return !/help|version|locale|approot|cldr|messages|output|argv/.test( option );
});

if ( extraOptions.length ) {
  console.log( "Invalid options:", extraOptions.join( ", " ), "\n" );
}

if ( opts.help || !requiredOpts || extraOptions.length ) {
  return console.log( help() );
}

var input = opts.argv.remain;
var messages = opts.messages;
var output = opts.output;
var approot = opts.approot

var messages = messages ? JSON.parse( fs.readFileSync( messages ) ) : null;

// preferred to get locales from those defined in messages file
if(!opts.locales){
  locales = Object.keys(messages)
} else {
  var locales = opts.locales.split(',');
}

var filesObj = GlobalizeCompilerPlus(input, messages, locales, approot)
var bundleObj = filesObj.formatters

mkdirp(output)

// write helpers
var filenames = Object.keys(filesObj)
for (var f in filenames){
  var filename = filenames[f]
  if(filename == "formatters"){
    continue
  }
  var filepath = path.join(output, filename)
  fs.writeFileSync(filepath, filesObj[filename])
}

locales = Object.keys(bundleObj)
for (var i in locales){
  var locale = locales[i]
  if(locale == "root"){
    continue
  }
  var filename = path.join(output, "formatters-" + locale + ".js").replace('\\', '/')
  var bundle = bundleObj[locale]
  fs.writeFileSync(filename, bundle);
}
<|endoftext|>


<commit_before>!function(){if(!window.CustomEvent&&document.createEventObject)return void(window.CustomEvent=function(e,t){if(!arguments.length)throw new Error("Not enough arguments");var s={type:e,bubbles:!1,cancelable:!1,detail:null},i=document.createEventObject();for(var n in s)i[n]=s[n];for(var n in t)i[n]=t[n];return i});try{new CustomEvent("test")}catch(e){var t=function(e,t){if(!arguments.length)throw new Error("Not enough arguments");var s={bubbles:!1,cancelable:!1,detail:null};for(var i in t)s[i]=t[i];var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,s.bubbles,s.cancelable,s.detail),n};t.prototype=(window.CustomEvent||window.Event).prototype,window.CustomEvent=t}}(),function(){if(!document.addEventListener&&window.Element&&window.Event){var e="__events",t="__immediateStopped";Event.prototype.NONE=Event.NONE=0,Event.prototype.CAPTURING_PHASE=Event.CAPTURING_PHASE=1,Event.prototype.AT_TARGET=Event.AT_TARGET=2,Event.prototype.BUBBLING_PHASE=Event.BUBBLING_PHASE=3,Event.prototype.preventDefault=function(){this.cancelable!==!1&&(this.returnValue=!1)},Event.prototype.stopPropagation=function(){this.cancelBubble=!0},Event.prototype.stopImmediatePropagation=function(){this[t]=this.cancelBubble=!0};for(var s=function(e,t){return e.timeStamp=+new Date,e.target||(e.target=e.srcElement||t),e.pageX=e.clientX+document.documentElement.scrollLeft,e.pageY=e.clientY+document.documentElement.scrollTop,e.relatedTarget="mouseover"==e.type?e.fromElement:"mouseout"==e.type?e.toElement:null,e},i=function(e,t,s){for(var i=0;i<e.length;i++){var n=e[i];if(n.useCapture==s&&n.listener==t)return i}return-1},n=function(e,t,s){e.currentTarget=s,"function"==typeof t?t.call(s,e):t.handleEvent(e)},a=function(e){for(var t=[];e.parentNode;)t.unshift(e.parentNode),e=e.parentNode;return t},o=function(s,i,a){s.eventPhase=a;for(var o=0;o<i.length;o++){for(var r=i[o],l=[],d=(r[e]||{})[s.type]||[],h=0;h<d.length;h++){var c=d[h];c.useCapture&&a==Event.BUBBLING_PHASE||(c.useCapture||a!=Event.CAPTURING_PHASE)&&l.push(c.listener)}for(h=0;h<l.length;)try{for(;h<l.length;){var u=l[h++];if(n(s,u,r),s[t])return!0}}catch(p){setTimeout(function(){throw p},0)}if(s.cancelBubble)return!0}return!1},r=function(e){s(e,this);var t=a(e.target);return t.length&&o(e,t,Event.CAPTURING_PHASE)?e.returnValue:o(e,[e.target],Event.AT_TARGET)?e.returnValue:t.length&&e.bubbles!==!1&&(t.reverse(),o(e,t,Event.BUBBLING_PHASE))?e.returnValue:(e.stopPropagation(),e.returnValue)},l=({addEventListener:function(t,s,n){var a=this,o=(this[e]||{})[t]||[],l=o.length;if(!(i(o,s,n)>-1)){if(e in this)var d=this[e];else{var d={_handler:function(){r.apply(a,arguments)}};this[e]=d}t in d||(d[t]=[]),d[t].push({listener:s,useCapture:n}),l||this.attachEvent("on"+t,d._handler)}},removeEventListener:function(t,s,n){var a=(this[e]||{})[t]||[],o=i(a,s,n);-1!=o&&(a.splice(o,1),a.length||this.detachEvent("on"+t,this[e]._handler))},dispatchEvent:function(e){return e.returnValue=!0,r.call(this,e)}}),d=[Element,window.constructor,document.constructor];d.length;){var h=d.pop();for(var c in l)h.prototype[c]=l[c]}}}(),Array.prototype.forEach||(Array.prototype.forEach=function(e,t){var s,i;if(null==this)throw new TypeError(" this is null or not defined");var n=Object(this),a=n.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(s=t),i=0;a>i;){var o;i in n&&(o=n[i],e.call(s,o,i,n)),i++}}),Array.prototype.indexOf||(Array.prototype.indexOf=function(e,t){var s;if(null==this)throw new TypeError('"this" is null or not defined');var i=Object(this),n=i.length>>>0;if(0===n)return-1;var a=+t||0;if(Math.abs(a)===1/0&&(a=0),a>=n)return-1;for(s=Math.max(a>=0?a:n-Math.abs(a),0);n>s;){if(s in i&&i[s]===e)return s;s++}return-1}),function(e){var t;if("object"==typeof exports){try{t=require("jquery")}catch(s){}module.exports=e(window,document,t)}else window.Dropkick=e(window,document,window.jQuery)}(function(e,t,s,i){var n,a=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),o=e.parent!==e.self&&location.host===parent.location.host,r=-1!==navigator.appVersion.indexOf("MSIE"),l=function(s,i){var n,a;if(this===e)return new l(s,i);for("string"==typeof s&&"#"===s[0]&&(s=t.getElementById(s.substr(1))),n=0;n<l.uid;n++)if(a=l.cache[n],a instanceof l&&a.data.select===s)return c.extend(a.data.settings,i),a;return s?"SELECT"===s.nodeName?this.init(s,i):void 0:(console.error("You must pass a select to DropKick"),!1)},d=function(){},h={initialize:d,change:d,open:d,close:d,search:"strict",bubble:!0},c={hasClass:function(e,t){var s=new RegExp("(^|\\s+)"+t+"(\\s+|$)");return e&&s.test(e.className)},addClass:function(e,t){e&&!c.hasClass(e,t)&&(e.className+=" "+t)},removeClass:function(e,t){var s=new RegExp("(^|\\s+)"+t+"(\\s+|$)");e&&(e.className=e.className.replace(s," "))},toggleClass:function(e,t){var s=c.hasClass(e,t)?"remove":"add";c[s+"Class"](e,t)},extend:function(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){if(t)for(var s in t)e[s]=t[s]}),e},offset:function(s){var i=s.getBoundingClientRect()||{top:0,left:0},n=t.documentElement,a=r?n.scrollTop:e.pageYOffset,o=r?n.scrollLeft:e.pageXOffset;return{top:i.top+a-n.clientTop,left:i.left+o-n.clientLeft}},position:function(e,t){for(var s={top:0,left:0};e&&e!==t;)s.top+=e.offsetTop,s.left+=e.offsetLeft,e=e.parentNode;return s},closest:function(e,t){for(;e;){if(e===t)return e;e=e.parentNode}return!1},create:function(e,s){var i,n=t.createElement(e);s||(s={});for(i in s)s.hasOwnProperty(i)&&("innerHTML"===i?n.innerHTML=s[i]:n.setAttribute(i,s[i]));return n},deferred:function(t){return function(){var s=arguments,i=this;e.setTimeout(function(){t.apply(i,s)},1)}}};return l.cache={},l.uid=0,l.prototype={add:function(e,s){var i,n,a;"string"==typeof e&&(i=e,e=t.createElement("option"),e.text=i),"OPTION"===e.nodeName&&(n=c.create("li",{"class":"dk-option","data-value":e.value,innerHTML:e.text,role:"option","aria-selected":"false",id:"dk"+this.data.cacheID+"-"+(e.id||e.value.replace(" ","-"))}),c.addClass(n,e.className),this.length+=1,e.disabled&&(c.addClass(n,"dk-option-disabled"),n.setAttribute("aria-disabled","true")),this.data.select.add(e,s),"number"==typeof s&&(s=this.item(s)),this.options.indexOf(s)>-1?s.parentNode.insertBefore(n,s):this.data.elem.lastChild.appendChild(n),n.addEventListener("mouseover",this),a=this.options.indexOf(s),this.options.splice(a,0,n),e.selected&&this.select(a))},item:function(e){return e=0>e?this.options.length+e:e,this.options[e]||null},remove:function(e){var t=this.item(e);t.parentNode.removeChild(t),this.options.splice(e,1),this.data.select.remove(e),this.select(this.data.select.selectedIndex),this.length-=1},init:function(e,s){var i,r=l.build(e,"dk"+l.uid);if(this.data={},this.data.select=e,this.data.elem=r.elem,this.data.settings=c.extend({},h,s),this.disabled=e.disabled,this.form=e.form,this.length=e.length,this.multiple=e.multiple,this.options=r.options.slice(0),this.selectedIndex=e.selectedIndex,this.selectedOptions=r.selected.slice(0),this.value=e.value,this.data.cacheID=l.uid,l.cache[this.data.cacheID]=this,this.data.settings.initialize.call(this),l.uid+=1,this._changeListener||(e.addEventListener("change",this),this._changeListener=!0),!a||this.data.settings.mobile){if(e.parentNode.insertBefore(this.data.elem,e),e.setAttribute("data-dkCacheId",this.data.cacheID),this.data.elem.addEventListener("click",this),this.data.elem.addEventListener("keydown",this),this.data.elem.addEventListener("keypress",this),this.form&&this.form.addEventListener("reset",this),!this.multiple)for(i=0;i<this.options.length;i++)this.options[i].addEventListener("mouseover",this);n||(t.addEventListener("click",l.onDocClick),o&&parent.document.addEventListener("click",l.onDocClick),n=!0)}return this},close:function(){var e,t=this.data.elem;if(!this.isOpen||this.multiple)return!1;for(e=0;e<this.options.length;e++)c.removeClass(this.options[e],"dk-option-highlight");t.lastChild.setAttribute("aria-expanded","false"),c.removeClass(t.lastChild,"dk-select-options-highlight"),c.removeClass(t,"dk-select-open-(up|down)"),this.isOpen=!1,this.data.settings.close.call(this)},open:c.deferred(function(){var s,i,n,a,o,l,d=this.data.elem,h=d.lastChild;return o=r?c.offset(d).top-t.documentElement.scrollTop:c.offset(d).top-e.scrollY,l=e.innerHeight-(o+d.offsetHeight),this.isOpen||this.multiple?!1:(h.style.display="block",s=h.offsetHeight,h.style.display="",i=o>s,n=l>s,a=i&&!n?"-up":"-down",this.isOpen=!0,c.addClass(d,"dk-select-open"+a),h.setAttribute("aria-expanded","true"),this._scrollTo(this.options.length-1),this._scrollTo(this.selectedIndex),void this.data.settings.open.call(this))}),disable:function(e,t){var s="dk-option-disabled";(0===arguments.length||"boolean"==typeof e)&&(t=e===i?!0:!1,e=this.data.elem,s="dk-select-disabled",this.disabled=t),t===i&&(t=!0),"number"==typeof e&&(e=this.item(e)),c[t?"addClass":"removeClass"](e,s)},select:function(e,t){var s,i,n,a,o=this.data.select;if("number"==typeof e&&(e=this.item(e)),"string"==typeof e)for(s=0;s<this.length;s++)this.options[s].getAttribute("data-value")===e&&(e=this.options[s]);return!e||"string"==typeof e||!t&&c.hasClass(e,"dk-option-disabled")?!1:c.hasClass(e,"dk-option")?(i=this.options.indexOf(e),n=o.options[i],this.multiple?(c.toggleClass(e,"dk-option-selected"),n.selected=!n.selected,c.hasClass(e,"dk-option-selected")?(e.setAttribute("aria-selected","true"),this.selectedOptions.push(e)):(e.setAttribute("aria-selected","false"),i=this.selectedOptions.indexOf(e),this.selectedOptions.splice(i,1))):(a=this.data.elem.firstChild,this.selectedOptions.length&&(c.removeClass(this.selectedOptions[0],"dk-option-selected"),this.selectedOptions[0].setAttribute("aria-selected","false")),c.addClass(e,"dk-option-selected"),e.setAttribute("aria-selected","true"),a.setAttribute("aria-activedescendant",e.id),a.className="dk-selected "+n.className,a.innerHTML=n.text,this.selectedOptions[0]=e,n.selected=!0),this.selectedIndex=o.selectedIndex,this.value=o.value,t||this.data.select.dispatchEvent(new CustomEvent("change",{bubbles:this.data.settings.bubble})),e):void 0},selectOne:function(e,t){return this.reset(!0),this._scrollTo(e),this.select(e,t)},search:function(e,t){var s,i,n,a,o,r,l,d,h=this.data.select.options,c=[];if(!e)return this.options;for(t=t?t.toLowerCase():"strict",t="fuzzy"===t?2:"partial"===t?1:0,d=new RegExp((t?"":"^")+e,"i"),s=0;s<h.length;s++)if(n=h[s].text.toLowerCase(),2==t){for(i=e.toLowerCase().split(""),a=o=r=l=0;o<n.length;)n[o]===i[a]?(r+=1+r,a++):r=0,l+=r,o++;a===i.length&&c.push({e:this.options[s],s:l,i:s})}else d.test(n)&&c.push(this.options[s]);return 2===t&&(c=c.sort(function(e,t){return t.s-e.s||e.i-t.i}).reduce(function(e,t){return e[e.length]=t.e,e},[])),c},focus:function(){this.disabled||(this.multiple?this.data.elem:this.data.elem.children[0]).focus()},reset:function(e){var t,s=this.data.select;for(this.selectedOptions.length=0,t=0;t<s.options.length;t++)s.options[t].selected=!1,c.removeClass(this.options[t],"dk-option-selected"),this.options[t].setAttribute("aria-selected","false"),!e&&s.options[t].defaultSelected&&this.select(t,!0);this.selectedOptions.length||this.multiple||this.select(0,!0)},refresh:function(){this.dispose().init(this.data.select,this.data.settings)},dispose:function(){return delete l.cache[this.data.cacheID],this.data.elem.parentNode.removeChild(this.data.elem),this.data.select.removeAttribute("data-dkCacheId"),this},handleEvent:function(e){if(!this.disabled)switch(e.type){case"click":this._delegate(e);break;case"keydown":this._keyHandler(e);break;case"keypress":this._searchOptions(e);break;case"mouseover":this._highlight(e);break;case"reset":this.reset();break;case"change":this.data.settings.change.call(this)}},_delegate:function(t){var s,i,n,a,o=t.target;if(c.hasClass(o,"dk-option-disabled"))return!1;if(this.multiple){if(c.hasClass(o,"dk-option"))if(s=e.getSelection(),"Range"===s.type&&s.collapseToStart(),t.shiftKey)if(n=this.options.indexOf(this.selectedOptions[0]),a=this.options.indexOf(this.selectedOptions[this.selectedOptions.length-1]),i=this.options.indexOf(o),i>n&&a>i&&(i=n),i>a&&a>n&&(a=n),this.reset(!0),a>i)for(;a+1>i;)this.select(i++);else for(;i>a-1;)this.select(i--);else t.ctrlKey||t.metaKey?this.select(o):(this.reset(!0),this.select(o))}else this[this.isOpen?"close":"open"](),c.hasClass(o,"dk-option")&&this.select(o)},_highlight:function(e){var t,s=e.target;if(!this.multiple){for(t=0;t<this.options.length;t++)c.removeClass(this.options[t],"dk-option-highlight");c.addClass(this.data.elem.lastChild,"dk-select-options-highlight"),c.addClass(s,"dk-option-highlight")}},_keyHandler:function(e){var t,s,i=this.selectedOptions,n=this.options,a=1,o={tab:9,enter:13,esc:27,space:32,up:38,down:40};switch(e.keyCode){case o.up:a=-1;case o.down:if(e.preventDefault(),t=i[i.length-1],c.hasClass(this.data.elem.lastChild,"dk-select-options-highlight"))for(c.removeClass(this.data.elem.lastChild,"dk-select-options-highlight"),s=0;s<n.length;s++)c.hasClass(n[s],"dk-option-highlight")&&(c.removeClass(n[s],"dk-option-highlight"),t=n[s]);a=n.indexOf(t)+a,a>n.length-1?a=n.length-1:0>a&&(a=0),this.data.select.options[a].disabled||(this.reset(!0),this.select(a),this._scrollTo(a));break;case o.space:if(!this.isOpen){e.preventDefault(),this.open();break}case o.tab:case o.enter:for(a=0;a<n.length;a++)c.hasClass(n[a],"dk-option-highlight")&&this.select(a);case o.esc:this.isOpen&&(e.preventDefault(),this.close())}},_searchOptions:function(e){var t,s=this,n=String.fromCharCode(e.keyCode||e.which),a=function(){s.data.searchTimeout&&clearTimeout(s.data.searchTimeout),s.data.searchTimeout=setTimeout(function(){s.data.searchString=""},1e3)};this.data.searchString===i&&(this.data.searchString=""),a(),this.data.searchString+=n,t=this.search(this.data.searchString,this.data.settings.search),t.length&&(c.hasClass(t[0],"dk-option-disabled")||this.selectOne(t[0]))},_scrollTo:function(e){var t,s,i,n=this.data.elem.lastChild;return-1===e||"number"!=typeof e&&!e||!this.isOpen&&!this.multiple?!1:("number"==typeof e&&(e=this.item(e)),t=c.position(e,n).top,s=t-n.scrollTop,i=s+e.offsetHeight,void(i>n.offsetHeight?(t+=e.offsetHeight,n.scrollTop=t-n.offsetHeight):0>s&&(n.scrollTop=t)))}},l.build=function(e,t){var s,i,n,a=[],o={elem:null,options:[],selected:[]},r=function(e){var s,i,n,a,l=[];switch(e.nodeName){case"OPTION":s=c.create("li",{"class":"dk-option ","data-value":e.value,innerHTML:e.text,role:"option","aria-selected":"false",id:t+"-"+(e.id||e.value.replace(" ","-"))}),c.addClass(s,e.className),e.disabled&&(c.addClass(s,"dk-option-disabled"),s.setAttribute("aria-disabled","true")),e.selected&&(c.addClass(s,"dk-option-selected"),s.setAttribute("aria-selected","true"),o.selected.push(s)),o.options.push(this.appendChild(s));break;case"OPTGROUP":for(i=c.create("li",{"class":"dk-optgroup"}),e.label&&i.appendChild(c.create("div",{"class":"dk-optgroup-label",innerHTML:e.label})),n=c.create("ul",{"class":"dk-optgroup-options"}),a=e.children.length;a--;l.unshift(e.children[a]));l.forEach(r,n),this.appendChild(i).appendChild(n)}};for(o.elem=c.create("div",{"class":"dk-select"+(e.multiple?"-multi":"")}),i=c.create("ul",{"class":"dk-select-options",id:t+"-listbox",role:"listbox"}),e.disabled&&c.addClass(o.elem,"dk-select-disabled"),o.elem.id=t+(e.id?"-"+e.id:""),c.addClass(o.elem,e.className),e.multiple?(o.elem.setAttribute("tabindex",e.getAttribute("tabindex")||"0"),i.setAttribute("aria-multiselectable","true")):(s=e.options[e.selectedIndex],o.elem.appendChild(c.create("div",{"class":"dk-selected "+s.className,tabindex:e.tabindex||0,innerHTML:s?s.text:" ",id:t+"-combobox","aria-live":"assertive","aria-owns":i.id,role:"combobox"})),i.setAttribute("aria-expanded","false")),n=e.children.length;n--;a.unshift(e.children[n]));return a.forEach(r,o.elem.appendChild(i)),o},l.onDocClick=function(e){var t,s;if(1!==e.target.nodeType)return!1;null!==(t=e.target.getAttribute("data-dkcacheid"))&&l.cache[t].focus();for(s in l.cache)c.closest(e.target,l.cache[s].data.elem)||s===t||l.cache[s].disabled||l.cache[s].close()},s!==i&&(s.fn.dropkick=function(){var e=Array.prototype.slice.call(arguments);return s(this).each(function(){e[0]&&"object"!=typeof e[0]?"string"==typeof e[0]&&l.prototype[e[0]].apply(new l(this),e.slice(1)):new l(this,e[0]||{})})}),l});<commit_msg>Remove dead min file<commit_after><|endoftext|>


<commit_before>var gulp = require('gulp');
var runSequence = require('run-sequence');
var paths = require('../paths');
var changelog = require('conventional-changelog');
var fs = require('fs');
var bump = require('gulp-bump');

gulp.task('bump-version', function(){
  return gulp.src(['./package.json'])
    .pipe(bump({type:'patch'})) //major|minor|patch|prerelease
    .pipe(gulp.dest('./'));
});

gulp.task('changelog', function(callback) {
  var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));

  return changelog({
    repository: pkg.repository.url,
    version: pkg.version,
    file: paths.doc + '/CHANGELOG.md'
  }, function(err, log) {
    fs.writeFileSync(paths.doc + '/CHANGELOG.md', log);
  });
});

gulp.task('prepare-release', function(callback){
  return runSequence(
    'build',
    'lint',
    'bump-version',
    'doc',
    'changelog',
    callback
  );
});
<commit_msg>fix(build): add missing bower bump<commit_after>var gulp = require('gulp');
var runSequence = require('run-sequence');
var paths = require('../paths');
var changelog = require('conventional-changelog');
var fs = require('fs');
var bump = require('gulp-bump');

gulp.task('bump-version', function(){
  return gulp.src(['./package.json', './bower.json'])
    .pipe(bump({type:'patch'})) //major|minor|patch|prerelease
    .pipe(gulp.dest('./'));
});

gulp.task('changelog', function(callback) {
  var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));

  return changelog({
    repository: pkg.repository.url,
    version: pkg.version,
    file: paths.doc + '/CHANGELOG.md'
  }, function(err, log) {
    fs.writeFileSync(paths.doc + '/CHANGELOG.md', log);
  });
});

gulp.task('prepare-release', function(callback){
  return runSequence(
    'build',
    'lint',
    'bump-version',
    'doc',
    'changelog',
    callback
  );
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Generates JSON output based on exportable symbols (those with
 * an api tag) and boolean defines (with a define tag and a default value).
 */
var assert = require('assert');
var fs = require('fs');
var path = require('path');

/**
 * Publish hook for the JSDoc template.  Writes to JSON stdout.
 * @param {function} data The root of the Taffy DB containing doclet records.
 * @param {Object} opts Options.
 */
exports.publish = function(data, opts) {

  function getTypes(data) {
    var types = [];
    data.forEach(function(name) {
      types.push(name.replace(/^function$/, 'Function'));
    });
    return types;
  }

  // get all doclets with the "api" property or define (excluding events) or
  // with olx namespace
  var docs = data(
      [
        {define: {isObject: true}},
        {api: {isString: true}},
        function() {
          return this.meta && (/[\\\/]externs$/).test(this.meta.path);
        }
      ],
      {kind: {'!is': 'file'}},
      {kind: {'!is': 'event'}}).get();

  // get symbols data, filter out those that are members of private classes
  var symbols = [];
  var defines = [];
  var typedefs = [];
  var externs = [];
  docs.filter(function(doc) {
    var include = true;
    var constructor = doc.memberof;
    if (constructor && constructor.substr(-1) === '_') {
      assert.strictEqual(doc.inherited, true,
          'Unexpected export on private class: ' + doc.longname);
      include = false;
    }
    return include;
  }).forEach(function(doc) {
    if (doc.longname.indexOf('olx.') === 0) {
      if (doc.kind == 'typedef') {
        typedefs.push({
          name: doc.longname,
          types: ['{}']
        });
      } else {
        var type = typedefs[typedefs.length - 1].types[0];
        typedefs[typedefs.length - 1].types[0] = type
            .replace(/\}$/, ', ' + doc.longname.split('#')[1] +
                ': (' + getTypes(doc.type.names).join('|') + ')}')
            .replace('{, ', '{');
      }
    } else if (doc.define) {
      defines.push({
        name: doc.longname,
        description: doc.description,
        path: path.join(doc.meta.path, doc.meta.filename),
        default: doc.define.default
      });
    } else if (doc.kind == 'typedef' || doc.isEnum === true) {
      typedefs.push({
        name: doc.longname,
        types: getTypes(doc.type.names)
      });
    } else {
      var types;
      var symbol = {
        name: doc.longname,
        kind: doc.kind,
        description: doc.classdesc || doc.description,
        path: path.join(doc.meta.path, doc.meta.filename)
      };
      if (doc.type) {
        symbol.types = getTypes(doc.type.names);
      }
      if (doc.params) {
        var params = [];
        doc.params.forEach(function(param) {
          var paramInfo = {
            name: param.name
          };
          params.push(paramInfo);
          paramInfo.types = getTypes(param.type.names);
          if (typeof param.variable == 'boolean') {
            paramInfo.variable = param.variable;
          }
          if (typeof param.optional == 'boolean') {
            paramInfo.optional = param.optional;
          }
        });
        symbol.params = params;
      }
      if (doc.returns) {
        symbol.returns = getTypes(doc.returns[0].type.names);
      }
      if (doc.tags) {
        doc.tags.every(function(tag) {
          if (tag.title == 'template') {
            symbol.template = tag.value;
            return false;
          }
          return true;
        });
      }
      var target = (/[\\\/]externs$/).test(doc.meta.path) ? externs : symbols;
      target.push(symbol);
    }
  });

  process.stdout.write(
      JSON.stringify({
        symbols: symbols,
        defines: defines,
        typedefs: typedefs,
        externs: externs
      }, null, 2));

};
<commit_msg>Build types only for olx.* symbols from externs<commit_after>/**
 * @fileoverview Generates JSON output based on exportable symbols (those with
 * an api tag) and boolean defines (with a define tag and a default value).
 */
var assert = require('assert');
var fs = require('fs');
var path = require('path');

/**
 * Publish hook for the JSDoc template.  Writes to JSON stdout.
 * @param {function} data The root of the Taffy DB containing doclet records.
 * @param {Object} opts Options.
 */
exports.publish = function(data, opts) {

  function getTypes(data) {
    var types = [];
    data.forEach(function(name) {
      types.push(name.replace(/^function$/, 'Function'));
    });
    return types;
  }

  // get all doclets with the "api" property or define (excluding events) or
  // with olx namespace
  var docs = data(
      [
        {define: {isObject: true}},
        {api: {isString: true}},
        function() {
          return this.meta && (/[\\\/]externs$/).test(this.meta.path);
        }
      ],
      {kind: {'!is': 'file'}},
      {kind: {'!is': 'event'}}).get();

  // get symbols data, filter out those that are members of private classes
  var symbols = [];
  var defines = [];
  var typedefs = [];
  var externs = [];
  docs.filter(function(doc) {
    var include = true;
    var constructor = doc.memberof;
    if (constructor && constructor.substr(-1) === '_') {
      assert.strictEqual(doc.inherited, true,
          'Unexpected export on private class: ' + doc.longname);
      include = false;
    }
    return include;
  }).forEach(function(doc) {
    var isExterns = (/[\\\/]externs$/).test(doc.meta.path);
    if (isExterns && doc.longname.indexOf('olx.') === 0) {
      if (doc.kind == 'typedef') {
        typedefs.push({
          name: doc.longname,
          types: ['{}']
        });
      } else {
        var type = typedefs[typedefs.length - 1].types[0];
        typedefs[typedefs.length - 1].types[0] = type
            .replace(/\}$/, ', ' + doc.longname.split('#')[1] +
                ': (' + getTypes(doc.type.names).join('|') + ')}')
            .replace('{, ', '{');
      }
    } else if (doc.define) {
      defines.push({
        name: doc.longname,
        description: doc.description,
        path: path.join(doc.meta.path, doc.meta.filename),
        default: doc.define.default
      });
    } else if (doc.kind == 'typedef' || doc.isEnum === true) {
      typedefs.push({
        name: doc.longname,
        types: getTypes(doc.type.names)
      });
    } else {
      var types;
      var symbol = {
        name: doc.longname,
        kind: doc.kind,
        description: doc.classdesc || doc.description,
        path: path.join(doc.meta.path, doc.meta.filename)
      };
      if (doc.type) {
        symbol.types = getTypes(doc.type.names);
      }
      if (doc.params) {
        var params = [];
        doc.params.forEach(function(param) {
          var paramInfo = {
            name: param.name
          };
          params.push(paramInfo);
          paramInfo.types = getTypes(param.type.names);
          if (typeof param.variable == 'boolean') {
            paramInfo.variable = param.variable;
          }
          if (typeof param.optional == 'boolean') {
            paramInfo.optional = param.optional;
          }
        });
        symbol.params = params;
      }
      if (doc.returns) {
        symbol.returns = getTypes(doc.returns[0].type.names);
      }
      if (doc.tags) {
        doc.tags.every(function(tag) {
          if (tag.title == 'template') {
            symbol.template = tag.value;
            return false;
          }
          return true;
        });
      }
      var target = isExterns ? externs : symbols;
      target.push(symbol);
    }
  });

  process.stdout.write(
      JSON.stringify({
        symbols: symbols,
        defines: defines,
        typedefs: typedefs,
        externs: externs
      }, null, 2));

};
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-drop-option', 'Integration | Component | sl drop option', {
    integration: true
});

test( 'Has expected initial class name', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'sl-drop-option' ),
        'Rendered component has class "sl-drop-option"'
    );

    assert.ok(
        this.$( '>:first-child' ).find( 'li' ),
        'Rendered componenet has the correct "li" tag'
    );
});

test( 'Has expected aria-role property', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).attr( 'role' ),
        'menuitem',
        'ARIA role is properly set to "menuitem"'
    );
});

test( 'Option type class value depends on `label` value', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'presentation' ),
        false,
        'Rendered component initially does not have class "presentation"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'divider' ),
        'Rendered component initially has class "divider"'
    );

    this.render( hbs`
        {{sl-drop-option label="test"}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'divider' ),
        false,
        'Rendered component does not have class "divider"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'presentation' ),
        'Rendered compnonet has class "presentation" with valid "label" value'
    );
});

test( 'label is present thus hyperlink tag is rendered', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.notOk(
        this.$( '>:first-child' ).find( 'a' ).attr( 'role' ),
        'Hyperlink is not rendered if label is not set'
    );

    this.render( hbs`
        {{sl-drop-option label="test"}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'a' ).attr( 'role' ),
        'menuitem',
        'Hyperlink is rendered if label is set'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'a' ).text().trim(),
        'test',
        'Hyperlink text is that of label value'
    );
});

test( 'if label is present and icon is set icon image tag is rendered with sample path', function( assert ) {
    this.render( hbs`
        {{sl-drop-option label="test"}}
    ` );

    assert.notOk(
        this.$( '>:first-child' ).find( 'img' ).attr( 'src' ),
        'Icon is not present thus img tag not set'
    );

    this.render( hbs`
        {{sl-drop-option label="test" icon="testDir/testImg.jpeg"}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'img' ).attr( 'src' ),
        'testDir/testImg.jpeg',
        'Icon is present with correct path and img tag is rendered with same path'
    );
});<commit_msg>added integration action test<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-drop-option', 'Integration | Component | sl drop option', {
    integration: true
});

test( 'Has expected initial class name', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'sl-drop-option' ),
        'Rendered component has class "sl-drop-option"'
    );

    assert.ok(
        this.$( '>:first-child' ).find( 'li' ),
        'Rendered componenet has the correct "li" tag'
    );
});

test( 'Has expected aria-role property', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).attr( 'role' ),
        'menuitem',
        'ARIA role is properly set to "menuitem"'
    );
});

test( 'Option type class value depends on `label` value', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'presentation' ),
        false,
        'Rendered component initially does not have class "presentation"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'divider' ),
        'Rendered component initially has class "divider"'
    );

    this.render( hbs`
        {{sl-drop-option label="test"}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'divider' ),
        false,
        'Rendered component does not have class "divider"'
    );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'presentation' ),
        'Rendered compnonet has class "presentation" with valid "label" value'
    );
});

test( 'label is present thus hyperlink tag is rendered', function( assert ) {
    this.render( hbs`
        {{sl-drop-option}}
    ` );

    assert.notOk(
        this.$( '>:first-child' ).find( 'a' ).attr( 'role' ),
        'Hyperlink is not rendered if label is not set'
    );

    this.render( hbs`
        {{sl-drop-option label="test"}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'a' ).attr( 'role' ),
        'menuitem',
        'Hyperlink is rendered if label is set'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'a' ).text().trim(),
        'test',
        'Hyperlink text is that of label value'
    );
});

test( 'if label is present and icon is set icon image tag is rendered with sample path', function( assert ) {
    this.render( hbs`
        {{sl-drop-option label="test"}}
    ` );

    assert.notOk(
        this.$( '>:first-child' ).find( 'img' ).attr( 'src' ),
        'Icon is not present thus img tag not set'
    );

    this.render( hbs`
        {{sl-drop-option label="test" icon="testDir/testImg.jpeg"}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( 'img' ).attr( 'src' ),
        'testDir/testImg.jpeg',
        'Icon is present with correct path and img tag is rendered with same path'
    );
});

test( 'Action fires when day is clicked', function( assert ) {
    assert.expect( 1 );

    this.set( 'testDataObject', { testProp: 'testValue'});

    this.render( hbs`
        {{sl-drop-option action="testAction" label="test"}}
    ` );

    this.on( 'testAction', () => {
        assert.ok(
            true,
            'The test action was called'
        );
    });

    this.$( '>:first-child' ).find( 'a' ).click();
});<|endoftext|>


<commit_before>function applyQuirks(text,pattern) {

    // Case
    try {
        switch (pattern.case) {
            case "lower":
                text = text.toLowerCase();
                break;
            case "upper":
                text = text.toUpperCase();
                break;
            case "title":
                text = text.toLowerCase().replace(/\b\w/g, function(t) { return t.toUpperCase(); });
                break;
            case "inverted":
                var text = text.replace(/[a-zA-Z]/g, function(t) {
                    var out = t.toUpperCase();
                    if (out==t) {
                        return t.toLowerCase();
                    } else {
                        return out;
                    }
                });
                break;
            case "alternating":
                var buffer = text.toLowerCase().split('');
                for(var i=0; i<buffer.length; i+=2){
                    buffer[i] = buffer[i].toUpperCase();
                }
                text = buffer.join('');
                break;
            case "alt-lines":
                if (pattern.line == 0) {
                    buffer = text.toLowerCase();
                } else {
                    buffer = text.toUpperCase();
                }
                text = buffer;
                break;
        }
    } catch(e) {}

    // Replacements
    try {
        var replace = {};
        for (i=0; i<pattern.replacements.length; i++) {
            var replacement = pattern.replacements[i];
            replace[replacement[0]] = replacement[1];
        }
    } catch(e) {
        replace = {};
    }

    try {
        var regex = {};
        for (i=0; i<pattern.regexes.length; i++) {
            var re = pattern.regexes[i];
            regex[re[0]] = re[1];
        }
    } catch(e) {
        regex = {};
    }

    var empty = true;
    for(var key in replace) {
        empty = false;
        break;
    }
    for(var key in regex) {
        empty = false;
        break;
    }

    try {
        if (!empty) {
            try {
                var replacementStrings = Object.keys(replace);
            } catch(e) {
                var replacementStrings = [];
            }
            for (i=0;i<replacementStrings.length;i++) {
                replacementStrings[i] = replacementStrings[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            }
            try {
                var regexStrings = Object.keys(regex);
            } catch(e) {
                var regexStrings = [];
            }
            if (replacementStrings.length!=0 && regexStrings.length!=0) {
                var reg_from = new RegExp(replacementStrings.join("|")+"|"+regexStrings.join("|"), "g");
            } else if (replacementStrings.length!=0 && regexStrings.length==0) {
                var reg_from = new RegExp(replacementStrings.join("|"), "g");
            } else if (replacementStrings.length==0 && regexStrings.length!=0) {
                var reg_from = new RegExp(regexStrings.join("|"), "g");
            } else {
                var reg_from = new RegExp("", "g");
            }
            text = text.replace(reg_from, function($1) {
                if (replace[$1]) {
                    return replace[$1]
                } else {
                    for (var reg in regexStrings) {
                        var original_text = $1;
                        if (RegExp(regexStrings[reg],'g').test($1)) {
                            var insert_text = regex[regexStrings[reg]];
                            insert_text = insert_text.replace(/([^\\]|^)(\$1)/g, function($1,$2,$3) {
                                return $2+original_text;
                            });
                            insert_text = insert_text.replace(/\\\$1/g, "\$1");
                            return insert_text;
                        }
                    }
                }
                return "";
            });
        }
    } catch(e) {}

    // Prefix
    if (pattern.quirk_prefix) {
        text = pattern.quirk_prefix+' '+text;
    }

    // Suffix
    if (pattern.quirk_suffix) {
        text = text+' '+pattern.quirk_suffix;
    }

    return text
}

function depunct(txt) {
    return txt.replace(/[.,?!']/g, '');
}<commit_msg>ios quirk error<commit_after>function applyQuirks(text,pattern) {

    // Case
    try {
        if (pattern.case) {
            switch (pattern.case) {
                case "lower":
                    text = text.toLowerCase();
                    break;
                case "upper":
                    text = text.toUpperCase();
                    break;
                case "title":
                    text = text.toLowerCase().replace(/\b\w/g, function(t) { return t.toUpperCase(); });
                    break;
                case "inverted":
                    text = text.replace(/[a-zA-Z]/g, function(t) {
                        var out = t.toUpperCase();
                        if (out==t) {
                            return t.toLowerCase();
                        } else {
                            return out;
                        }
                    });
                    break;
                case "alternating":
                    var buffer = text.toLowerCase().split('');
                    for(var i=0; i<buffer.length; i+=2){
                        buffer[i] = buffer[i].toUpperCase();
                    }
                    text = buffer.join('');
                    break;
                case "alt-lines":
                    if (pattern.line == 0) {
                        buffer = text.toLowerCase();
                    } else {
                        buffer = text.toUpperCase();
                    }
                    text = buffer;
                    break;
            }
        }
    } catch(e) {}

    // Replacements
    try {
        var replace = {};
        for (i=0; i<pattern.replacements.length; i++) {
            var replacement = pattern.replacements[i];
            replace[replacement[0]] = replacement[1];
        }
    } catch(e) {
        replace = {};
    }

    try {
        var regex = {};
        for (i=0; i<pattern.regexes.length; i++) {
            var re = pattern.regexes[i];
            regex[re[0]] = re[1];
        }
    } catch(e) {
        regex = {};
    }

    var empty = true;
    for(var key in replace) {
        empty = false;
        break;
    }
    for(var key in regex) {
        empty = false;
        break;
    }

    try {
        if (!empty) {
            try {
                var replacementStrings = Object.keys(replace);
            } catch(e) {
                var replacementStrings = [];
            }
            for (i=0;i<replacementStrings.length;i++) {
                replacementStrings[i] = replacementStrings[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            }
            try {
                var regexStrings = Object.keys(regex);
            } catch(e) {
                var regexStrings = [];
            }
            if (replacementStrings.length!=0 && regexStrings.length!=0) {
                var reg_from = new RegExp(replacementStrings.join("|")+"|"+regexStrings.join("|"), "g");
            } else if (replacementStrings.length!=0 && regexStrings.length==0) {
                var reg_from = new RegExp(replacementStrings.join("|"), "g");
            } else if (replacementStrings.length==0 && regexStrings.length!=0) {
                var reg_from = new RegExp(regexStrings.join("|"), "g");
            } else {
                var reg_from = new RegExp("", "g");
            }
            text = text.replace(reg_from, function($1) {
                if (replace[$1]) {
                    return replace[$1]
                } else {
                    for (var reg in regexStrings) {
                        var original_text = $1;
                        if (RegExp(regexStrings[reg],'g').test($1)) {
                            var insert_text = regex[regexStrings[reg]];
                            insert_text = insert_text.replace(/([^\\]|^)(\$1)/g, function($1,$2,$3) {
                                return $2+original_text;
                            });
                            insert_text = insert_text.replace(/\\\$1/g, "\$1");
                            return insert_text;
                        }
                    }
                }
                return "";
            });
        }
    } catch(e) {}

    // Prefix
    if (pattern.quirk_prefix) {
        text = pattern.quirk_prefix+' '+text;
    }

    // Suffix
    if (pattern.quirk_suffix) {
        text = text+' '+pattern.quirk_suffix;
    }

    return text
}

function depunct(txt) {
    return txt.replace(/[.,?!']/g, '');
}<|endoftext|>


<commit_before>/**
 * A FreeDOM interface to Chrome sockets
 * TODO(willscott): Refactor into freedom-chrome.
 * @constructor
 * @private
 */
var Socket_chrome = function(channel) {
  this.appChannel = channel;
  this.sid = null;
  this.create = chrome.socket.create;
  this.connect = chrome.socket.connect;
  this.read = chrome.socket.read;
  this.write = chrome.socket.write;
};

Socket_chrome.prototype.destroy = function(socketId, continuation) {
  if (chrome && chrome.socket) {
    chrome.socket.destroy(socketId);
  }
  continuation();
};

Socket_chrome.prototype.disconnect = function(socketId, continuation) {
  if (chrome && chrome.socket) {
    chrome.socket.disconnect(socketId);
  }
  continuation();
};
<commit_msg>add chrome backing to server sockets<commit_after>/**
 * A FreeDOM interface to Chrome sockets
 * TODO(willscott): Refactor into freedom-chrome.
 * @constructor
 * @private
 */
var Socket_chrome = function(channel) {
  this.appChannel = channel;
  this.sid = null;
  this.create = chrome.socket.create;
  this.connect = chrome.socket.connect;
  this.read = chrome.socket.read;
  this.write = chrome.socket.write;
  this.listen = chrome.socket.listen;
  this.accept = chrome.socket.accept;
  this.getInfo = chrome.socket.getInfo;
};

Socket_chrome.prototype.destroy = function(socketId, continuation) {
  if (chrome && chrome.socket) {
    chrome.socket.destroy(socketId);
  }
  continuation();
};

Socket_chrome.prototype.disconnect = function(socketId, continuation) {
  if (chrome && chrome.socket) {
    chrome.socket.disconnect(socketId);
  }
  continuation();
};
<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React, { useCallback, useState } from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import Button from "@agir/front/genericComponents/Button";
import CSRFProtectedForm from "@agir/front/genericComponents/CSRFProtectedForm";
import FeatherIcon, {
  RawFeatherIcon,
} from "@agir/front/genericComponents/FeatherIcon";
import Popin from "@agir/front/genericComponents/Popin";

const StyledPanel = styled.div`
  width: 100%;
  background-color: ${style.primary100};
  padding: 1.5rem;
  margin: 0;

  @media (max-width: ${style.collapse}px) {
    display: none;
  }

  h6 {
    margin: 0;
    font-size: 1rem;
    line-height: 1;
    color: ${style.primary500};
    margin-bottom: 1rem;
    font-weight: bold;
  }

  && ul {
    margin-bottom: 0;

    li {
      align-items: center;
      font-weight: normal;
      font-size: 0.875rem;

      a {
        margin-left: 0.5rem;
      }

      ${RawFeatherIcon} {
        svg {
          stroke-width: 2px;
          width: 1rem;
          height: 1rem;
        }
      }
    }
  }

  ${Button} + ul {
    margin-top: 1rem;
  }

  & ~ ${Button} {
    @media (min-width: ${style.collapse}px) {
      display: none;
    }
  }
`;
const StyledContent = styled.div`
  padding: 0;
  display: flex;
  align-items: flex-start;
  flex-flow: column nowrap;
  margin-bottom: 2rem;

  @media (max-width: ${style.collapse}px) {
    background-color: white;
    width: 100%;
    padding: 0 1rem 1.5rem;
    margin-bottom: 0;
    align-items: center;
    display: ${({ hideOnMobile }) => (hideOnMobile ? "none" : "flex")};
  }

  & > ${Button} {
    margin: 0;
    width: 100%;
    justify-content: center;
  }

  & > ${Button} + ${Button} {
    margin-top: 0.75rem;
  }

  p {
    margin-top: 0.5rem;
    font-weight: 500;
    font-size: 0.813rem;
    line-height: 1.5;
    color: ${style.black500};

    @media (max-width: ${style.collapse}px) {
      font-size: 0.688rem;
      font-weight: 400;
      color: ${style.black1000};
      margin-bottom: 0;
    }
  }

  ul {
    list-style: none;
    padding: 0;
    margin: 0;

    li {
      font-size: 0.813rem;
      line-height: 1.3;
      display: flex;
      align-items: baseline;

      a {
        color: ${style.black1000};
        margin-left: 0.5rem;
      }
    }

    li + li {
      margin-top: 0.5rem;
    }
  }
`;

const GroupLinks = (props) => {
  const { isMember, isManager, is2022 = false, routes } = props;

  const [isPopinOpen, setIsPopinOpen] = useState(false);
  const openPopin = useCallback(() => setIsPopinOpen(true), []);
  const closePopin = useCallback(() => setIsPopinOpen(false), []);

  if (isManager) {
    return (

        <Button
          as="a"
          href={routes.createEvent}
          color="primary"
          icon="plus"
          small
        >
          Créer un événement {is2022 ? "de l'équipe" : "du groupe"}
        </Button>
        <Button as="a" href={routes.settings} icon="settings" small>
          Gestion {is2022 ? "de l'équipe" : "du groupe"}
        </Button>
      </StyledContent>
    );
  }

  if (isMember && routes.quit) {
    return (

    );
  }

  return (

  );
};

GroupLinks.propTypes = {
  isMember: PropTypes.bool,
  isManager: PropTypes.bool,
  is2022: PropTypes.bool,
  routes: PropTypes.object,
};
export default GroupLinks;
<commit_msg>fix: restore GroupUserActions Member version on small screens<commit_after>import PropTypes from "prop-types";
import React, { useCallback, useState } from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import Button from "@agir/front/genericComponents/Button";
import CSRFProtectedForm from "@agir/front/genericComponents/CSRFProtectedForm";
import FeatherIcon, {
  RawFeatherIcon,
} from "@agir/front/genericComponents/FeatherIcon";
import Popin from "@agir/front/genericComponents/Popin";
import BottomSheet from "@agir/front/genericComponents/BottomSheet";
import { ResponsiveLayout } from "@agir/front/genericComponents/grid";

const StyledList = styled.ul`
  width: 100%;
  cursor: pointer;
  display: flex;
  flex-flow: column nowrap;
  align-items: stretch;
  list-style: none;
  color: ${style.primary500};
  padding: 0;

  @media (max-width: ${style.collapse}px) {
    margin: 0;
    padding: 1.5rem;
  }

  a {
    display: flex;
    align-items: center;
    border: none;
    padding: 0;
    margin: 0;
    text-decoration: none;
    background: inherit;
    cursor: pointer;
    text-align: center;
    -webkit-appearance: none;
    -moz-appearance: none;
    font-size: 0.875rem;
    line-height: 20px;
    font-weight: 400;
    color: ${style.black1000};
    margin-bottom: 0.5rem;

    &:last-child {
      margin-bottom: 0;
    }

    &:hover,
    &:focus {
      text-decoration: underline;
      border: none;
      outline: none;
    }

    &[disabled],
    &[disabled]:hover,
    &[disabled]:focus {
      opacity: 0.75;
      text-decoration: none;
      cursor: default;
    }

    @media (max-width: ${style.collapse}px) {
      margin-bottom: 1.5rem;
      text-decoration: none;
    }

    & > *:first-child {
      margin-right: 0.5rem;
      width: 1rem;
      height: 1rem;

      @media (max-width: ${style.collapse}px) {
        margin-right: 1rem;-
        width: 1.5rem;
        height: 1.5rem;
      }

      svg {
        width: inherit;
        height: inherit;
        stroke-width: 2;
      }
    }
  }
`;
const StyledPanel = styled.div`
  width: 100%;
  background-color: ${style.primary100};
  padding: 1.5rem;
  margin: 0;

  @media (max-width: ${style.collapse}px) {
    display: none;
  }

  h6 {
    margin: 0;
    font-size: 1rem;
    line-height: 1;
    color: ${style.primary500};
    margin-bottom: 1rem;
    font-weight: bold;
  }

  && ul {
    margin-bottom: 0;

    li {
      align-items: center;
      font-weight: normal;
      font-size: 0.875rem;

      a {
        margin-left: 0.5rem;
      }

      ${RawFeatherIcon} {
        svg {
          stroke-width: 2px;
          width: 1rem;
          height: 1rem;
        }
      }
    }
  }

  ${Button} + ul {
    margin-top: 1rem;
  }

  & ~ ${Button} {
    @media (min-width: ${style.collapse}px) {
      display: none;
    }
  }
`;
const StyledContent = styled.div`
  padding: 0;
  display: flex;
  align-items: flex-start;
  flex-flow: column nowrap;
  margin-bottom: 2rem;

  @media (max-width: ${style.collapse}px) {
    background-color: white;
    width: 100%;
    padding: 0 1rem 1.5rem;
    margin-bottom: 0;
    align-items: center;
    display: ${({ hideOnMobile }) => (hideOnMobile ? "none" : "flex")};
  }

  & > ${Button} {
    margin: 0;
    width: 100%;
    justify-content: center;
  }

  & > ${Button} + ${Button} {
    margin-top: 0.75rem;
  }

  p {
    margin-top: 0.5rem;
    font-weight: 500;
    font-size: 0.813rem;
    line-height: 1.5;
    color: ${style.black500};

    @media (max-width: ${style.collapse}px) {
      font-size: 0.688rem;
      font-weight: 400;
      color: ${style.black1000};
      margin-bottom: 0;
    }
  }
`;

const ManagerActions = (props) => {
  const { is2022 = false, routes } = props;

  return (

      <Button
        as="a"
        href={routes.createEvent}
        color="primary"
        icon="plus"
        small
      >
        Créer un événement {is2022 ? "de l'équipe" : "du groupe"}
      </Button>
      <Button as="a" href={routes.settings} icon="settings" small>
        Gestion {is2022 ? "de l'équipe" : "du groupe"}
      </Button>
    </StyledContent>
  );
};

const MobileMemberActions = (props) => {
  const { is2022 = false, routes, isMenuOpen, openMenu, closeMenu } = props;

  return (

      <Button onClick={openMenu} color="default" icon="check" small>
        Vous êtes membre {is2022 ? "de l'équipe" : "du groupe"}
      </Button>
      <BottomSheet isOpen={isMenuOpen} onDismiss={closeMenu} position="bottom">

      </BottomSheet>

  );
};
const DesktopMemberActions = (props) => {
  const { is2022 = false, routes, isMenuOpen, openMenu, closeMenu } = props;

  return (

      <Button onClick={openMenu} color="default" icon="check">
        Vous êtes membre {is2022 ? "de l'équipe" : "du groupe"}
      </Button>
      <Popin isOpen={isMenuOpen} onDismiss={closeMenu} position="bottom">

      </Popin>

  );
};
DesktopMemberActions.propTypes = MobileMemberActions.propTypes = {
  is2022: PropTypes.bool,
  routes: PropTypes.object,
  isMenuOpen: PropTypes.bool,
  openMenu: PropTypes.func,
  closeMenu: PropTypes.func,
};
const MemberActions = (props) => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const openMenu = useCallback(() => setIsMenuOpen(true), []);
  const closeMenu = useCallback(() => setIsMenuOpen(false), []);

  return (

  );
};

const NonMemberActions = (props) => {
  const { is2022 = false, routes } = props;

  return (

  );
};

const GroupUserActions = (props) => {
  if (props.isManager) {
    return <ManagerActions {...props} />;
  }
  if (props.isMember) {
    return <MemberActions {...props} />;
  }
  return <NonMemberActions {...props} />;
};

ManagerActions.propTypes = MemberActions.propTypes = NonMemberActions.propTypes = GroupUserActions.propTypes = {
  isMember: PropTypes.bool,
  isManager: PropTypes.bool,
  is2022: PropTypes.bool,
  routes: PropTypes.object,
};
export default GroupUserActions;
<|endoftext|>


<commit_before>var GridStatesManager = {
  // do ajax save
  saveStates: function(gridName, type, value){
    var url = "/wulin_master/grid_states/save",
    data = decodeURIComponent($.param({ grid_name: gridName, state_type: type, state_value: value,
                                        authenticity_token: window._token }));
    $.post(url, data, function(response){
    });
  },

  // grid events
  onStateEvents: function(grid) {
    var self = this;

    // save columns width when columns resized
    grid.onColumnsResized.subscribe(function(){
      var widthJson = {};
      $.each(this.getColumns(), function(index, column){
        widthJson[column.id] = column.width;
      });
      self.saveStates(grid.name, "width", widthJson);
    });

    // save columns sorting info when columns sorted
    grid.onSort.subscribe(function(e, args){
      var loader = grid.loader, sortJson = {};
      sortJson["sortCol"] = loader.getSortColumn();
      sortJson["sortDir"] = loader.getSortDirection();
      self.saveStates(grid.name, "sort", sortJson);
    });

    // save columns order when columns re-ordered
    grid.onColumnsReordered.subscribe(function(e, args){
      var orderJson = {};
      $.each(this.getColumns(), function(index, column){
        orderJson[index] = column.id;
      });

      self.saveStates(grid.name, "order", orderJson);
    });

    // save filter states when input filter value
    grid.filterPanel.onFilterLoaded.subscribe(function(e, args){
      var filterJson = {};
      $.each(args.filterData, function(index,data){
        filterJson[data['id']] = data['value'];
      });
      self.saveStates(grid.name, "filter", filterJson);
    });

    // save columns visibility when pick columns
    if(grid.picker){
      grid.picker.onColumnsPick.subscribe(function(e, args){
        var visibilityJson = {};
        $.each(grid.getColumns(), function(index, column){
          visibilityJson[index] = column.id;
        });

        self.saveStates(grid.name, "visibility", visibilityJson);
      })
    }
  },

  // Restore columns order states
  restoreOrderStates: function(columns, orderStates){
	  if(!orderStates) return columns;

	  var new_columns = [], i, j, k;
    // find id column
    for(i in columns){
      if (columns[i].id == "id"){
        new_columns.push(columns[i]);
        break;
      }
    }
		// push other columns according to states
		for(j in orderStates){
		  for(k in columns) {
		    if(columns[k].id == orderStates[j]){
		      new_columns.push(columns[k]);
		      break;
		    }
		  }
		}
		// push columns that are not in the state in abritrary order
		for(i in columns) {
	    var found = false;
	    for(j in new_columns) {
	      if (columns[i].id == new_columns[j].id) {
	        found = true;
	      }
	    }
	    if (found==false) {
	      new_columns.push(columns[i]);
	    }
	  }
		return new_columns;
	},

	// Restore columns visibility states
	restoreVisibilityStates: function(columns, visibilityStates) {
	  if(!visibilityStates) return false;

	  // push visible columns according to states
	  for(var i in columns){
	    var visible = false;
	    for(var j in visibilityStates){
	      if(columns[i].id == visibilityStates[j]){
	        visible = true;
	        break;
	      }
	    }
	    columns[i].visible = visible;
	  }
	},

	// Restore columns width states
	restoreWidthStates: function(columns, widthStates) {
	  if(!widthStates) return false;

    // restore width
    for(var i in widthStates){
      for(var j in columns){
        if(columns[j].id == i){
          columns[j].width = parseInt(widthStates[i]);
          break;
        }
      }
    }
	},

	// Restore columns sorting states
	restoreSortingStates: function(grid, loader, sortingStates) {
	  if(sortingStates){
      grid.setSortColumn(sortingStates["sortCol"], sortingStates["sortDir"] == 1);
	    loader.setSort(sortingStates["sortCol"], sortingStates["sortDir"]);
	  }
	},

	// Apply current filters
	applayFilters: function(path, filterStates) {
	  if (filterStates) {
  	  $.each(filterStates, function(k, v){
  	    path += "&filters[][column]=" + k + "&filters[][value]=" + v;
  	  })
    }
	  return path;
	}

}

<commit_msg>BUG - Also fix state save for filter containing % character<commit_after>var GridStatesManager = {
  // do ajax save
  saveStates: function(gridName, type, value){
    var url = "/wulin_master/grid_states/save",
    data = decodeURIComponent($.param({ grid_name: encodeURIComponent(gridName),
                                        state_type: encodeURIComponent(type),
                                        state_value: encodeURIComponent(value),
                                        authenticity_token: window._token }));
    $.post(url, data, function(response){
    });
  },

  // grid events
  onStateEvents: function(grid) {
    var self = this;

    // save columns width when columns resized
    grid.onColumnsResized.subscribe(function(){
      var widthJson = {};
      $.each(this.getColumns(), function(index, column){
        widthJson[column.id] = column.width;
      });
      self.saveStates(grid.name, "width", widthJson);
    });

    // save columns sorting info when columns sorted
    grid.onSort.subscribe(function(e, args){
      var loader = grid.loader, sortJson = {};
      sortJson["sortCol"] = loader.getSortColumn();
      sortJson["sortDir"] = loader.getSortDirection();
      self.saveStates(grid.name, "sort", sortJson);
    });

    // save columns order when columns re-ordered
    grid.onColumnsReordered.subscribe(function(e, args){
      var orderJson = {};
      $.each(this.getColumns(), function(index, column){
        orderJson[index] = column.id;
      });

      self.saveStates(grid.name, "order", orderJson);
    });

    // save filter states when input filter value
    grid.filterPanel.onFilterLoaded.subscribe(function(e, args){
      var filterJson = {};
      $.each(args.filterData, function(index,data){
        filterJson[data['id']] = data['value'];
      });
      self.saveStates(grid.name, "filter", filterJson);
    });

    // save columns visibility when pick columns
    if(grid.picker){
      grid.picker.onColumnsPick.subscribe(function(e, args){
        var visibilityJson = {};
        $.each(grid.getColumns(), function(index, column){
          visibilityJson[index] = column.id;
        });

        self.saveStates(grid.name, "visibility", visibilityJson);
      })
    }
  },

  // Restore columns order states
  restoreOrderStates: function(columns, orderStates){
	  if(!orderStates) return columns;

	  var new_columns = [], i, j, k;
    // find id column
    for(i in columns){
      if (columns[i].id == "id"){
        new_columns.push(columns[i]);
        break;
      }
    }
		// push other columns according to states
		for(j in orderStates){
		  for(k in columns) {
		    if(columns[k].id == orderStates[j]){
		      new_columns.push(columns[k]);
		      break;
		    }
		  }
		}
		// push columns that are not in the state in abritrary order
		for(i in columns) {
	    var found = false;
	    for(j in new_columns) {
	      if (columns[i].id == new_columns[j].id) {
	        found = true;
	      }
	    }
	    if (found==false) {
	      new_columns.push(columns[i]);
	    }
	  }
		return new_columns;
	},

	// Restore columns visibility states
	restoreVisibilityStates: function(columns, visibilityStates) {
	  if(!visibilityStates) return false;

	  // push visible columns according to states
	  for(var i in columns){
	    var visible = false;
	    for(var j in visibilityStates){
	      if(columns[i].id == visibilityStates[j]){
	        visible = true;
	        break;
	      }
	    }
	    columns[i].visible = visible;
	  }
	},

	// Restore columns width states
	restoreWidthStates: function(columns, widthStates) {
	  if(!widthStates) return false;

    // restore width
    for(var i in widthStates){
      for(var j in columns){
        if(columns[j].id == i){
          columns[j].width = parseInt(widthStates[i]);
          break;
        }
      }
    }
	},

	// Restore columns sorting states
	restoreSortingStates: function(grid, loader, sortingStates) {
	  if(sortingStates){
      grid.setSortColumn(sortingStates["sortCol"], sortingStates["sortDir"] == 1);
	    loader.setSort(sortingStates["sortCol"], sortingStates["sortDir"]);
	  }
	},

	// Apply current filters
	applayFilters: function(path, filterStates) {
	  if (filterStates) {
  	  $.each(filterStates, function(k, v){
  	    path += "&filters[][column]=" + k + "&filters[][value]=" + v;
  	  })
    }
	  return path;
	}

}

<|endoftext|>


<commit_before>/**
 *                        WHITEBOPHIR
 *********************************************************
 * @licstart  The following is the entire license notice for the
 *  JavaScript code in this page.
 *
 * Copyright (C) 2013  Ophir LOJKINE
 *
 *
 * The JavaScript code in this page is free software: you can
 * redistribute it and/or modify it under the terms of the GNU
 * General Public License (GNU GPL) as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version.  The code is distributed WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
 *
 * As additional permission under GNU GPL version 3 section 7, you
 * may distribute non-source (e.g., minimized or compacted) forms of
 * that code without the copy of the GNU GPL normally required by
 * section 4, provided you include this license notice and a URL
 * through which recipients can access the Corresponding Source.
 *
 * @licend
 */

(function () { //Code isolation
    var ZOOM_FACTOR = .5;
    var origin = {
        scrollX: window.scrollX,
        scrollY: window.scrollY,
        x: 0.0,
        y: 0.0,
        clientY: 0,
        scale: 1.0
    };
    var moved = false, pressed = false;

    function zoom(origin, scale) {
        var oldScale = origin.scale;
        var newScale = Tools.setScale(scale);
        window.scrollTo(
            origin.scrollX + origin.x * (newScale - oldScale),
            origin.scrollY + origin.y * (newScale - oldScale)
        );
    }

    var animation = null;
    function animate(scale) {
        cancelAnimationFrame(animation);
        animation = requestAnimationFrame(function () {
            zoom(origin, scale);
        });
    }

    function setOrigin(x, y, evt, isTouchEvent) {
        origin.scrollX = window.scrollX;
        origin.scrollY = window.scrollY;
        origin.x = x;
        origin.y = y;
        origin.clientY = getClientY(evt, isTouchEvent);
        origin.scale = Tools.getScale();
    }

    function press(x, y, evt, isTouchEvent) {
        evt.preventDefault();
        setOrigin(x, y, evt, isTouchEvent);
        moved = false;
        pressed = true;
    }

    function move(x, y, evt, isTouchEvent) {
        if (pressed) {
            evt.preventDefault();
            var delta = getClientY(evt, isTouchEvent) - origin.clientY;
            var scale = origin.scale * (1 + delta * ZOOM_FACTOR / 100);
            if (Math.abs(delta) > 1) moved = true;
            animation = animate(scale);
        }
    }

    function onwheel(evt) {
        evt.preventDefault();
        if (evt.ctrlKey || Tools.curTool === zoomTool) {
            var scale = Tools.getScale();
            var x = evt.pageX / scale;
            var y = evt.pageY / scale;
            setOrigin(x, y, evt, false);
            animate((1 - ((evt.deltaY > 0) - (evt.deltaY < 0)) * 0.25) * Tools.getScale());
        } else {
            window.scrollTo(window.scrollX + evt.deltaX, window.scrollY + evt.deltaY);
        }
    }
    Tools.board.addEventListener("wheel", onwheel, { passive: false });

    Tools.board.addEventListener("touchmove", function ontouchmove(evt) {
        // 2-finger pan to zoom
        var touches = evt.touches;
        if (touches.length === 2) {
            var x0 = touches[0].clientX, x1 = touches[1].clientX,
                y0 = touches[0].clientY, y1 = touches[1].clientY,
                dx = x0 - x1,
                dy = y0 - y1;
            var x = (touches[0].pageX + touches[1].pageX) / 2 / Tools.getScale(),
                y = (touches[0].pageY + touches[1].pageY) / 2 / Tools.getScale();
            var distance = Math.sqrt(dx * dx + dy * dy);
            if (!pressed) {
                pressed = true;
                setOrigin(x, y, evt, true);
                origin.distance = distance;
            } else {
                var delta = distance - origin.distance;
                var scale = origin.scale * (1 + delta * ZOOM_FACTOR / 100);
                animate(scale);
            }
        }
    }, { passive: true });
    function touchend() {
        pressed = false;
    }
    Tools.board.addEventListener("touchend", touchend);
    Tools.board.addEventListener("touchcancel", touchend);

    function release(x, y, evt, isTouchEvent) {
        if (pressed && !moved) {
            var delta = (evt.shiftKey === true) ? -1 : 1;
            var scale = Tools.getScale() * (1 + delta * ZOOM_FACTOR);
            zoom(origin, scale);
        }
        pressed = false;
    }

    function key(down) {
        return function (evt) {
            if (evt.key === "Shift") {
                Tools.svg.style.cursor = "zoom-" + (down ? "out" : "in");
            }
        }
    }

    function getClientY(evt, isTouchEvent) {
        return isTouchEvent ? evt.changedTouches[0].clientY : evt.clientY;
    }

    var keydown = key(true);
    var keyup = key(false);

    function onstart() {
        window.addEventListener("keydown", keydown);
        window.addEventListener("keyup", keyup);
    }
    function onquit() {
        window.removeEventListener("keydown", keydown);
        window.removeEventListener("keyup", keyup);
    }

    var zoomTool = {
        "name": "Zoom",
		"shortcut": "z",
        "listeners": {
            "press": press,
            "move": move,
            "release": release,
        },
        "onstart": onstart,
        "onquit": onquit,
        "mouseCursor": "zoom-in",
        "icon": "tools/zoom/icon.svg",
        "helpText": "click_to_zoom",
    };
    Tools.add(zoomTool);
})(); //End of code isolation
<commit_msg>swap scroll axis when holding shift (#53)<commit_after>/**
 *                        WHITEBOPHIR
 *********************************************************
 * @licstart  The following is the entire license notice for the
 *  JavaScript code in this page.
 *
 * Copyright (C) 2013  Ophir LOJKINE
 *
 *
 * The JavaScript code in this page is free software: you can
 * redistribute it and/or modify it under the terms of the GNU
 * General Public License (GNU GPL) as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version.  The code is distributed WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
 *
 * As additional permission under GNU GPL version 3 section 7, you
 * may distribute non-source (e.g., minimized or compacted) forms of
 * that code without the copy of the GNU GPL normally required by
 * section 4, provided you include this license notice and a URL
 * through which recipients can access the Corresponding Source.
 *
 * @licend
 */

(function () { //Code isolation
    var ZOOM_FACTOR = .5;
    var origin = {
        scrollX: window.scrollX,
        scrollY: window.scrollY,
        x: 0.0,
        y: 0.0,
        clientY: 0,
        scale: 1.0
    };
    var moved = false, pressed = false;

    function zoom(origin, scale) {
        var oldScale = origin.scale;
        var newScale = Tools.setScale(scale);
        window.scrollTo(
            origin.scrollX + origin.x * (newScale - oldScale),
            origin.scrollY + origin.y * (newScale - oldScale)
        );
    }

    var animation = null;
    function animate(scale) {
        cancelAnimationFrame(animation);
        animation = requestAnimationFrame(function () {
            zoom(origin, scale);
        });
    }

    function setOrigin(x, y, evt, isTouchEvent) {
        origin.scrollX = window.scrollX;
        origin.scrollY = window.scrollY;
        origin.x = x;
        origin.y = y;
        origin.clientY = getClientY(evt, isTouchEvent);
        origin.scale = Tools.getScale();
    }

    function press(x, y, evt, isTouchEvent) {
        evt.preventDefault();
        setOrigin(x, y, evt, isTouchEvent);
        moved = false;
        pressed = true;
    }

    function move(x, y, evt, isTouchEvent) {
        if (pressed) {
            evt.preventDefault();
            var delta = getClientY(evt, isTouchEvent) - origin.clientY;
            var scale = origin.scale * (1 + delta * ZOOM_FACTOR / 100);
            if (Math.abs(delta) > 1) moved = true;
            animation = animate(scale);
        }
    }

    function onwheel(evt) {
        evt.preventDefault();
        if (evt.ctrlKey || Tools.curTool === zoomTool) {
            var scale = Tools.getScale();
            var x = evt.pageX / scale;
            var y = evt.pageY / scale;
            setOrigin(x, y, evt, false);
            animate((1 - ((evt.deltaY > 0) - (evt.deltaY < 0)) * 0.25) * Tools.getScale());
        } else if (evt.shiftKey) {
            window.scrollTo(window.scrollX + evt.deltaY, window.scrollY + evt.deltaX);
        } else {
            window.scrollTo(window.scrollX + evt.deltaX, window.scrollY + evt.deltaY);
        }
    }
    Tools.board.addEventListener("wheel", onwheel, { passive: false });

    Tools.board.addEventListener("touchmove", function ontouchmove(evt) {
        // 2-finger pan to zoom
        var touches = evt.touches;
        if (touches.length === 2) {
            var x0 = touches[0].clientX, x1 = touches[1].clientX,
                y0 = touches[0].clientY, y1 = touches[1].clientY,
                dx = x0 - x1,
                dy = y0 - y1;
            var x = (touches[0].pageX + touches[1].pageX) / 2 / Tools.getScale(),
                y = (touches[0].pageY + touches[1].pageY) / 2 / Tools.getScale();
            var distance = Math.sqrt(dx * dx + dy * dy);
            if (!pressed) {
                pressed = true;
                setOrigin(x, y, evt, true);
                origin.distance = distance;
            } else {
                var delta = distance - origin.distance;
                var scale = origin.scale * (1 + delta * ZOOM_FACTOR / 100);
                animate(scale);
            }
        }
    }, { passive: true });
    function touchend() {
        pressed = false;
    }
    Tools.board.addEventListener("touchend", touchend);
    Tools.board.addEventListener("touchcancel", touchend);

    function release(x, y, evt, isTouchEvent) {
        if (pressed && !moved) {
            var delta = (evt.shiftKey === true) ? -1 : 1;
            var scale = Tools.getScale() * (1 + delta * ZOOM_FACTOR);
            zoom(origin, scale);
        }
        pressed = false;
    }

    function key(down) {
        return function (evt) {
            if (evt.key === "Shift") {
                Tools.svg.style.cursor = "zoom-" + (down ? "out" : "in");
            }
        }
    }

    function getClientY(evt, isTouchEvent) {
        return isTouchEvent ? evt.changedTouches[0].clientY : evt.clientY;
    }

    var keydown = key(true);
    var keyup = key(false);

    function onstart() {
        window.addEventListener("keydown", keydown);
        window.addEventListener("keyup", keyup);
    }
    function onquit() {
        window.removeEventListener("keydown", keydown);
        window.removeEventListener("keyup", keyup);
    }

    var zoomTool = {
        "name": "Zoom",
		"shortcut": "z",
        "listeners": {
            "press": press,
            "move": move,
            "release": release,
        },
        "onstart": onstart,
        "onquit": onquit,
        "mouseCursor": "zoom-in",
        "icon": "tools/zoom/icon.svg",
        "helpText": "click_to_zoom",
    };
    Tools.add(zoomTool);
})(); //End of code isolation
<|endoftext|>