<commit_before>var _ = require('underscore'),
    async = require('async'),
    fs = require('fs'),
    path = require('path'),
    utils = require('./utils').utils,
    excelParser = {};

excelParser.worksheets = function(options, cb) {
  var worksheets, cb = cb && typeof(cb) === "function" ? cb : null, args = [];
  if(!cb) throw new Error("worksheets will required two arguments. worksheets(options, callback)")
  else if(!options || typeof(options) !== 'object') return cb("Invalid arguments.");
  else if(!options.inFile) return cb("File is missing in arguments");

  fs.exists(options.inFile, function(exists) {
    if(!exists) return cb("File not found");
    args = ['-x', '"'+path.relative(__dirname, options.inFile)+'"', '-W'];
    utils.execute(args, function(err, stdout) {
      if(err) return cb(err);
      worksheets = _.compact(stdout.split(/\n/));
      if(worksheets) return cb(null, JSON.parse(worksheets));
      else return cb(new Error("Not found any worksheet in given spreadsheet"));
    });
  });
};

excelParser.parse = function(options, cb) {
  var args = [], _this = this;
  if(!cb) throw new Error("worksheets will required two arguments. worksheets(options, callback)");
  else if(!options || typeof(options) !== 'object') return cb("Invalid arguments.");
  else if(!options.inFile) return cb("File is missing in arguments");
  fs.exists(options.inFile, function(exists) {
    if(!exists) return cb("File not found");
    args = ['-x', '"'+path.relative(__dirname, options.inFile)+'"'];
    if(!options.worksheet) {
      var records = [];
      _this.worksheets(options, function(err, worksheets) {
        if(err) return cb(err);
        async.series(_.map(worksheets, function(worksheet) {
          return function(rcb) {
            args.push('-n', worksheet.id);
            utils.pickRecords(args, options, function(err, parsed) {
              if(err) return cb(err);
              records.push(parsed);
              rcb(null);
            });
          }
        }), function(err, parsed) {
          if(err) return cb(err);
          cb(null, parsed);
        });
      });
    } else {
      if(typeof(options.worksheet) === 'number') {
        args.push('-n', options.worksheet);
      } else if(typeof(options.worksheet) === 'string') {
        args.push('-w', '"'+ options.worksheet.trim() + '"');
      } else {
        return callback(new Error('"worksheet" should be string or intiger'));
      }
      utils.pickRecords(args, options, function(err, parsed) {
        if(err) return cb(err);
        cb(null, parsed);
      });
    }
  });
};
module.exports = excelParser;<commit_msg>bug fix for parsing multiple sheet<commit_after>var _ = require('underscore'),
    async = require('async'),
    fs = require('fs'),
    path = require('path'),
    utils = require('./utils').utils,
    excelParser = {};

excelParser.worksheets = function(options, cb) {
  var worksheets, cb = cb && typeof(cb) === "function" ? cb : null, args = [];
  if(!cb) throw new Error("worksheets will required two arguments. worksheets(options, callback)")
  else if(!options || typeof(options) !== 'object') return cb("Invalid arguments.");
  else if(!options.inFile) return cb("File is missing in arguments");

  fs.exists(options.inFile, function(exists) {
    if(!exists) return cb("File not found");
    args = ['-x', '"'+path.relative(__dirname, options.inFile)+'"', '-W'];
    utils.execute(args, function(err, stdout) {
      if(err) return cb(err);
      worksheets = _.compact(stdout.split(/\n/));
      if(worksheets) return cb(null, JSON.parse(worksheets));
      else return cb(new Error("Not found any worksheet in given spreadsheet"));
    });
  });
};

excelParser.parse = function(options, cb) {
  var args = [], _this = this;
  if(!cb) throw new Error("worksheets will required two arguments. worksheets(options, callback)");
  else if(!options || typeof(options) !== 'object') return cb("Invalid arguments.");
  else if(!options.inFile) return cb("File is missing in arguments");
  fs.exists(options.inFile, function(exists) {
    if(!exists) return cb("File not found");
    args = ['-x', '"'+path.relative(__dirname, options.inFile)+'"'];
    if(!options.worksheet) {
      var records = [];
      _this.worksheets(options, function(err, worksheets) {
        if(err) return cb(err);
        async.series(_.map(worksheets, function(worksheet) {
          return function(rcb) {
            args.push('-n', worksheet.id);
            utils.pickRecords(args, options, function(err, parsed) {
              if(err) return cb(err);
              records.push(parsed);
              rcb(null);
            });
          }
        }), function(err, parsed) {
          if(err) return cb(err);
          cb(null, records);
        });
      });
    } else {
      if(typeof(options.worksheet) === 'number') {
        args.push('-n', options.worksheet);
      } else if(typeof(options.worksheet) === 'string') {
        args.push('-w', '"'+ options.worksheet.trim() + '"');
      } else {
        return callback(new Error('"worksheet" should be string or intiger'));
      }
      utils.pickRecords(args, options, function(err, parsed) {
        if(err) return cb(err);
        cb(null, parsed);
      });
    }
  });
};
module.exports = excelParser;<|endoftext|>


<commit_before>/**
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *    User interface shared components, requires opnsense.js for supporting functions.
 */

/**
 * save form to server
 * @param url endpoint url
 * @param formid parent id to grep input data from
 * @param disable_dialog don't show input validation message box on failure
 */
function saveFormToEndpoint(url,formid,callback_ok, disable_dialog) {
    disable_dialog = disable_dialog || false;
    var data = getFormData(formid);
    ajaxCall(url=url,sendData=data,callback=function(data,status){
        if ( status == "success") {
            // update field validation
            handleFormValidation(formid,data['validations']);

            // if there are validation issues, update our screen and show a dialog.
            if (data['validations'] != undefined) {
                if (!disable_dialog) {
                    // validation message box is optional, form is already updated using handleFormValidation
                    BootstrapDialog.show({
                        type:BootstrapDialog.TYPE_WARNING,
                        title: 'Input validation',
                        message: 'Please correct validation errors in form',
                        buttons: [{
                            label: 'Dismiss',
                            action: function(dialogRef){
                                dialogRef.close();
                            }
                        }]

                    });
                }
            } else if ( callback_ok != undefined ) {
                // execute callback function
                callback_ok();
            }

        } else {
            // error handling, show internal errors
            // Normally the form should only return validation issues, if other things go wrong throw an error.
            BootstrapDialog.show({
                type: BootstrapDialog.TYPE_ERROR,
                title: 'save',
                message: 'Unable to save data, an internal error occurred.
 ' +
                'Response from server was:
 '+JSON.stringify(data)+''
            });
        }

    });
}

/**
 * standard data mapper to map json request data to forms on this page
 * @param data_get_map named array containing form names and source url's to get data from {'frm_example':"/api/example/settings/get"};
 * @return promise object, resolves when all are loaded
 */
function mapDataToFormUI(data_get_map) {
    var dfObj = new $.Deferred();

    // calculate number of items for deferred object to resolve
    var data_map_seq = 1;
    var data_map_count = 0;
    $.each(data_get_map, function(){
        data_map_count += 1;
    });

    $.each(data_get_map, function(data_index, data_url) {
        ajaxGet(url=data_url,sendData={}, callback=function(data, status) {
            if (status == "success") {
                $("form").each(function( index ) {
                    if ( $(this).attr('id').split('-')[0] == data_index) {
                        // related form found, load data
                        setFormData($(this).attr('id'), data);
                    }
                });
            }
            if (data_map_seq == data_map_count) {
                dfObj.resolve(data_map_seq);
            }
            data_map_seq += 1;
        });
    });

    return dfObj;
}

/**
 * update service status buttons in user interface
 */
function updateServiceStatusUI(status) {

    var status_html = '';

    if (status == "running") {
        status_html += '' ;
    } else if (status == "stopped") {
        status_html += '' ;
    } else {
        status_html += '' ;
    }

    status_html += '  ';

    $('#service_status_container').html(status_html);
}

/**
 * reformat all tokenizers on this document
 */
function formatTokenizersUI(){
    $('select[class="tokenize"]').each(function(){
        if ($(this).prop("size")==0) {
            maxDropdownHeight=String(36*5)+"px"; // default number of items

        } else {
            number_of_items = $(this).prop("size");
            maxDropdownHeight=String(36*number_of_items)+"px";
        }
        hint=$(this).data("hint");
        width=$(this).data("width");
        allownew=$(this).data("allownew");
        maxTokenContainerHeight=$(this).data("maxheight");

        $(this).tokenize({
            displayDropdownOnFocus: true,
            newElements: allownew,
            placeholder:hint
        });
        $(this).parent().find('ul[class="TokensContainer"]').parent().css("width",width);
        $(this).parent().find('ul[class="Dropdown"]').css("max-height", maxDropdownHeight);
        if ( maxDropdownHeight != undefined ) {
            $(this).parent().find('ul[class="TokensContainer"]').css("max-height", maxTokenContainerHeight);
        }
    });
}

/**
 * clear multiselect boxes on click event, works on standard and tokenized versions
 */
function addMultiSelectClearUI() {
    $('[id*="clear-options"]').each(function() {
        $(this).click(function() {
            var id = $(this).attr("for");
            BootstrapDialog.confirm({
                title: 'Deselect or remove all items ?',
                message: 'Deselect or remove all items ?',
                type: BootstrapDialog.TYPE_DANGER,
                closable: true,
                draggable: true,
                btnCancelLabel: 'Cancel',
                btnOKLabel: 'Yes',
                btnOKClass: 'btn-primary',
                callback: function(result) {
                    if(result) {
                        if ($('select[id="' + id + '"]').hasClass("tokenize")) {
                            // trigger close on all Tokens
                            $('select[id="' + id + '"]').parent().find('ul[class="TokensContainer"]').find('li[class="Token"]').find('a').trigger("click");
                        } else {
                            // remove options from selection
                            $('select[id="' + id + '"]').find('option').prop('selected',false);
                        }
                    }
                }
            });
        });
    });
}

/**
 * setup form help buttons
 */
function initFormHelpUI() {
    // handle help messages show/hide
    $("a[class='showhelp']").click(function () {
        $("*[for='" + $(this).attr('id') + "']").toggleClass("hidden show");
    });

    // handle all help messages show/hide
    $('[id*="show_all_help"]').click(function() {
        $('[id*="show_all_help"]').toggleClass("fa-toggle-on fa-toggle-off");
        $('[id*="show_all_help"]').toggleClass("text-success text-danger");
        if ($('[id*="show_all_help"]').hasClass("fa-toggle-on")) {
            $('[for*="help_for"]').addClass("show");
            $('[for*="help_for"]').removeClass("hidden");
        } else {
            $('[for*="help_for"]').addClass("hidden");
            $('[for*="help_for"]').removeClass("show");
        }
    });
}

/**
 * handle advanced show/hide
 */
function initFormAdvancedUI() {
    $('[data-advanced*="true"]').hide(function(){
        $('[data-advanced*="true"]').after("

"); // the table row is added to keep correct table striping
    });
    $('[id*="show_advanced"]').click(function() {
        $('[id*="show_advanced"]').toggleClass("fa-toggle-on fa-toggle-off");
        $('[id*="show_advanced"]').toggleClass("text-success text-danger");
        if ($('[id*="show_advanced"]').hasClass("fa-toggle-on")) {
            $('[data-advanced*="true"]').show();
            $('[data-advanced*="hidden_row"]').remove(); // the table row is deleted to keep correct table striping
        } else {
            $('[data-advanced*="true"]').after("

").hide(); // the table row is added to keep correct table striping
        }
    });
}

/**
 * standard remove items dialog, wrapper around BootstrapDialog
 */
function stdDialogRemoveItem(message, callback) {
    BootstrapDialog.confirm({
        title: 'Remove',
        message: message,
        type:BootstrapDialog.TYPE_WARNING,
        btnCancelLabel: 'Cancel',
        btnOKLabel: 'Yes',
        btnOKClass: 'btn-primary',
        callback: function(result) {
            if(result) {
                callback();
            }
        }
    });
}
<commit_msg>(mvc) pass collected data from mapDataToFormUI to deferred objects<commit_after>/**
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *    User interface shared components, requires opnsense.js for supporting functions.
 */

/**
 * save form to server
 * @param url endpoint url
 * @param formid parent id to grep input data from
 * @param disable_dialog don't show input validation message box on failure
 */
function saveFormToEndpoint(url,formid,callback_ok, disable_dialog) {
    disable_dialog = disable_dialog || false;
    var data = getFormData(formid);
    ajaxCall(url=url,sendData=data,callback=function(data,status){
        if ( status == "success") {
            // update field validation
            handleFormValidation(formid,data['validations']);

            // if there are validation issues, update our screen and show a dialog.
            if (data['validations'] != undefined) {
                if (!disable_dialog) {
                    // validation message box is optional, form is already updated using handleFormValidation
                    BootstrapDialog.show({
                        type:BootstrapDialog.TYPE_WARNING,
                        title: 'Input validation',
                        message: 'Please correct validation errors in form',
                        buttons: [{
                            label: 'Dismiss',
                            action: function(dialogRef){
                                dialogRef.close();
                            }
                        }]

                    });
                }
            } else if ( callback_ok != undefined ) {
                // execute callback function
                callback_ok();
            }

        } else {
            // error handling, show internal errors
            // Normally the form should only return validation issues, if other things go wrong throw an error.
            BootstrapDialog.show({
                type: BootstrapDialog.TYPE_ERROR,
                title: 'save',
                message: 'Unable to save data, an internal error occurred.
 ' +
                'Response from server was:
 '+JSON.stringify(data)+''
            });
        }

    });
}

/**
 * standard data mapper to map json request data to forms on this page
 * @param data_get_map named array containing form names and source url's to get data from {'frm_example':"/api/example/settings/get"};
 * @return promise object, resolves when all are loaded
 */
function mapDataToFormUI(data_get_map) {
    var dfObj = new $.Deferred();

    // calculate number of items for deferred object to resolve
    var data_map_seq = 1;
    var data_map_count = 0;
    $.each(data_get_map, function(){
        data_map_count += 1;
    });

    var collected_data = {};
    $.each(data_get_map, function(data_index, data_url) {
        ajaxGet(url=data_url,sendData={}, callback=function(data, status) {
            if (status == "success") {
                $("form").each(function( index ) {
                    if ( $(this).attr('id').split('-')[0] == data_index) {
                        // related form found, load data
                        setFormData($(this).attr('id'), data);
                        collected_data[$(this).attr('id')] = data;
                    }
                });
            }
            if (data_map_seq == data_map_count) {
                dfObj.resolve(collected_data);
            }
            data_map_seq += 1;
        });
    });

    return dfObj;
}

/**
 * update service status buttons in user interface
 */
function updateServiceStatusUI(status) {

    var status_html = '';

    if (status == "running") {
        status_html += '' ;
    } else if (status == "stopped") {
        status_html += '' ;
    } else {
        status_html += '' ;
    }

    status_html += '  ';

    $('#service_status_container').html(status_html);
}

/**
 * reformat all tokenizers on this document
 */
function formatTokenizersUI(){
    $('select[class="tokenize"]').each(function(){
        if ($(this).prop("size")==0) {
            maxDropdownHeight=String(36*5)+"px"; // default number of items

        } else {
            number_of_items = $(this).prop("size");
            maxDropdownHeight=String(36*number_of_items)+"px";
        }
        hint=$(this).data("hint");
        width=$(this).data("width");
        allownew=$(this).data("allownew");
        maxTokenContainerHeight=$(this).data("maxheight");

        $(this).tokenize({
            displayDropdownOnFocus: true,
            newElements: allownew,
            placeholder:hint
        });
        $(this).parent().find('ul[class="TokensContainer"]').parent().css("width",width);
        $(this).parent().find('ul[class="Dropdown"]').css("max-height", maxDropdownHeight);
        if ( maxDropdownHeight != undefined ) {
            $(this).parent().find('ul[class="TokensContainer"]').css("max-height", maxTokenContainerHeight);
        }
    });
}

/**
 * clear multiselect boxes on click event, works on standard and tokenized versions
 */
function addMultiSelectClearUI() {
    $('[id*="clear-options"]').each(function() {
        $(this).click(function() {
            var id = $(this).attr("for");
            BootstrapDialog.confirm({
                title: 'Deselect or remove all items ?',
                message: 'Deselect or remove all items ?',
                type: BootstrapDialog.TYPE_DANGER,
                closable: true,
                draggable: true,
                btnCancelLabel: 'Cancel',
                btnOKLabel: 'Yes',
                btnOKClass: 'btn-primary',
                callback: function(result) {
                    if(result) {
                        if ($('select[id="' + id + '"]').hasClass("tokenize")) {
                            // trigger close on all Tokens
                            $('select[id="' + id + '"]').parent().find('ul[class="TokensContainer"]').find('li[class="Token"]').find('a').trigger("click");
                        } else {
                            // remove options from selection
                            $('select[id="' + id + '"]').find('option').prop('selected',false);
                        }
                    }
                }
            });
        });
    });
}

/**
 * setup form help buttons
 */
function initFormHelpUI() {
    // handle help messages show/hide
    $("a[class='showhelp']").click(function () {
        $("*[for='" + $(this).attr('id') + "']").toggleClass("hidden show");
    });

    // handle all help messages show/hide
    $('[id*="show_all_help"]').click(function() {
        $('[id*="show_all_help"]').toggleClass("fa-toggle-on fa-toggle-off");
        $('[id*="show_all_help"]').toggleClass("text-success text-danger");
        if ($('[id*="show_all_help"]').hasClass("fa-toggle-on")) {
            $('[for*="help_for"]').addClass("show");
            $('[for*="help_for"]').removeClass("hidden");
        } else {
            $('[for*="help_for"]').addClass("hidden");
            $('[for*="help_for"]').removeClass("show");
        }
    });
}

/**
 * handle advanced show/hide
 */
function initFormAdvancedUI() {
    $('[data-advanced*="true"]').hide(function(){
        $('[data-advanced*="true"]').after("

"); // the table row is added to keep correct table striping
    });
    $('[id*="show_advanced"]').click(function() {
        $('[id*="show_advanced"]').toggleClass("fa-toggle-on fa-toggle-off");
        $('[id*="show_advanced"]').toggleClass("text-success text-danger");
        if ($('[id*="show_advanced"]').hasClass("fa-toggle-on")) {
            $('[data-advanced*="true"]').show();
            $('[data-advanced*="hidden_row"]').remove(); // the table row is deleted to keep correct table striping
        } else {
            $('[data-advanced*="true"]').after("

").hide(); // the table row is added to keep correct table striping
        }
    });
}

/**
 * standard remove items dialog, wrapper around BootstrapDialog
 */
function stdDialogRemoveItem(message, callback) {
    BootstrapDialog.confirm({
        title: 'Remove',
        message: message,
        type:BootstrapDialog.TYPE_WARNING,
        btnCancelLabel: 'Cancel',
        btnOKLabel: 'Yes',
        btnOKClass: 'btn-primary',
        callback: function(result) {
            if(result) {
                callback();
            }
        }
    });
}
<|endoftext|>


<commit_before>module.exports = {
  BarChart: require('./components/BarChart'),
  Button: require('./components/Button'),
  ButtonGroup: require('./components/ButtonGroup'),
  Calendar: require('./components/Calendar'),
  Column: require('./components/grid/Column'),
  Container: require('./components/grid/Container'),
  DatePicker: require('./components/DatePicker'),
  DatePickerFullScreen: require('./components/DatePickerFullScreen'),
  DateRangePicker: require('./components/DateRangePicker'),
  DateTimePicker: require('./components/DateTimePicker'),
  DisplayInput: require('./components/DisplayInput'),
  DonutChart: require('./components/DonutChart'),
  Drawer: require('./components/Drawer'),
  FileUpload: require('./components/FileUpload'),
  Gauge: require('./components/Gauge'),
  Icon: require('./components/Icon'),
  Loader: require('./components/Loader'),
  Menu: require('./components/Menu'),
  Modal: require('./components/Modal'),
  PageIndicator: require('./components/PageIndicator'),
  ProgressBar: require('./components/ProgressBar'),
  RadioButton: require('./components/RadioButton'),
  RajaIcon: require('./components/RajaIcon'),
  Row: require('./components/grid/Row'),
  RangeSelector: require('./components/RangeSelector'),
  SearchInput: require('./components/SearchInput'),
  Select: require('./components/Select'),
  SelectFullScreen: require('./components/SelectFullScreen'),
  SimpleInput: require('./components/SimpleInput'),
  SimpleSelect: require('./components/SimpleSelect'),
  SimpleSlider: require('./components/SimpleSlider'),
  Spin: require('./components/Spin'),
  Tabs: require('./components/Tabs'),
  TextArea: require('./components/TextArea'),
  TimeBasedLineChart: require('./components/TimeBasedLineChart'),
  ToggleSwitch: require('./components/ToggleSwitch'),
  Tooltip: require('./components/Tooltip'),
  TypeAhead: require('./components/TypeAhead'),

  // D3 components
  AxisGroup: require('./components/d3/AxisGroup'),
  BreakPointGroup: require('./components/d3/BreakPointGroup'),
  CirclesGroup: require('./components/d3/CirclesGroup'),
  GridLinesGroup: require('./components/d3/GridLinesGroup'),
  LineGroup: require('./components/d3/LineGroup'),
  ShadedAreaRectangleGroup: require('./components/d3/ShadedAreaRectangleGroup'),
  ShadedHatchPatternRectangleGroup: require('./components/d3/ShadedHatchPatternRectangleGroup'),
  SlicesGroup: require('./components/d3/SlicesGroup'),
  TimeXAxisGroup: require('./components/d3/TimeXAxisGroup'),

  // App constants
  AppConstants: require('./constants/App'),
  Styles: require('./constants/Style')
};
<commit_msg>Exports ChartUtils<commit_after>module.exports = {
  BarChart: require('./components/BarChart'),
  Button: require('./components/Button'),
  ButtonGroup: require('./components/ButtonGroup'),
  Calendar: require('./components/Calendar'),
  Column: require('./components/grid/Column'),
  Container: require('./components/grid/Container'),
  DatePicker: require('./components/DatePicker'),
  DatePickerFullScreen: require('./components/DatePickerFullScreen'),
  DateRangePicker: require('./components/DateRangePicker'),
  DateTimePicker: require('./components/DateTimePicker'),
  DisplayInput: require('./components/DisplayInput'),
  DonutChart: require('./components/DonutChart'),
  Drawer: require('./components/Drawer'),
  FileUpload: require('./components/FileUpload'),
  Gauge: require('./components/Gauge'),
  Icon: require('./components/Icon'),
  Loader: require('./components/Loader'),
  Menu: require('./components/Menu'),
  Modal: require('./components/Modal'),
  PageIndicator: require('./components/PageIndicator'),
  ProgressBar: require('./components/ProgressBar'),
  RadioButton: require('./components/RadioButton'),
  RajaIcon: require('./components/RajaIcon'),
  Row: require('./components/grid/Row'),
  RangeSelector: require('./components/RangeSelector'),
  SearchInput: require('./components/SearchInput'),
  Select: require('./components/Select'),
  SelectFullScreen: require('./components/SelectFullScreen'),
  SimpleInput: require('./components/SimpleInput'),
  SimpleSelect: require('./components/SimpleSelect'),
  SimpleSlider: require('./components/SimpleSlider'),
  Spin: require('./components/Spin'),
  Tabs: require('./components/Tabs'),
  TextArea: require('./components/TextArea'),
  TimeBasedLineChart: require('./components/TimeBasedLineChart'),
  ToggleSwitch: require('./components/ToggleSwitch'),
  Tooltip: require('./components/Tooltip'),
  TypeAhead: require('./components/TypeAhead'),

  // D3 components
  AxisGroup: require('./components/d3/AxisGroup'),
  BreakPointGroup: require('./components/d3/BreakPointGroup'),
  CirclesGroup: require('./components/d3/CirclesGroup'),
  GridLinesGroup: require('./components/d3/GridLinesGroup'),
  LineGroup: require('./components/d3/LineGroup'),
  ShadedAreaRectangleGroup: require('./components/d3/ShadedAreaRectangleGroup'),
  ShadedHatchPatternRectangleGroup: require('./components/d3/ShadedHatchPatternRectangleGroup'),
  SlicesGroup: require('./components/d3/SlicesGroup'),
  TimeXAxisGroup: require('./components/d3/TimeXAxisGroup'),

  // App constants
  AppConstants: require('./constants/App'),
  Styles: require('./constants/Style'),

  // App Utils
  ChartUtils: require('./utils/Chart')
};
<|endoftext|>


<commit_before>(function() {

  var callbacksCount = 1;
  var callbacks = {};

  var isArray = Array.isArray || function(obj) {
    return obj instanceof Array;
  };

  var extend = function(obj, source) {
    if (!source) return obj;

    for (var prop in source) {
      if (source[prop] !== undefined)
        obj[prop] = source[prop];
    }

    return obj;
  };

  var emptyFn = function() {}

  var Efte = {

    send_message: function(method, args, callback) {
      // console.log('send_message', arguments);
      var hasCallback = callback && typeof callback == 'function';
      var callbackId = hasCallback ? callbacksCount++ : 0;
      if (hasCallback) callbacks[callbackId] = callback;

      args['callbackId'] = callbackId;
      args = (typeof args === 'object') ? JSON.stringify(args) : args + '';
      var ifr = document.createElement('iframe');
      ifr.style.display = 'none';
      document.body.appendChild(ifr);
      ifr.contentWindow.location.href = 'js://_?method=' + method + '&args=' + encodeURIComponent(args) + '&callbackId=' + callbackId;
      // ifr.parentNode.removeChild(ifr);
      setTimeout(function() {
        ifr.parentNode.removeChild(ifr);
      }, 0);

      return callbackId;
    },

    callback: function(callbackId, retValue) {
      try {
        var callback = callbacks[callbackId];
        if (!callback) return;
        callback.apply(null, [retValue]);
        // delete callbacks[callbackId];
      } catch (e) {
        alert(e);
      }
    },

    ajax: function(opts) {
      var success = opts.success || emptyFn;
      var fail = opts.fail || emptyFn;

      // null data lead native error
      if (!opts.data) {
        delete opts.data;
      }

      var callbackID = Efte.send_message('ajax', opts, function(json) {
        var errMsg = '';
        if (json.code == 0) {
          var rsp = null;
          try {
            rsp = JSON.parse(json.responseText);
            success(rsp);
            delete callbacks[callbackID];
          } catch (e) {
            fail(-2, 'parse json error: ' + e.message);
            console.log(json);
            delete callbacks[callbackID];
          }
        } else {
          fail(json.code, json.message);
          delete callbacks[callbackID];
        }
      });
      return {
        cancel: function() {
          delete callbacks[callbackID];
        }
      };
    },

    action: {
      get: function(callback) {
        var cid = Efte.send_message('actionGetQuery', {}, function(query) {
          if (typeof callback != 'function') return;
          callback(query);
          delete callbacks[cid];
        });
      },
      open: function(unit, path, query, modal, animated) {
        modal = !!modal;
        if (animated === undefined) {
          animated = true;
        }
        var cid = Efte.send_message('actionOpen', {
          unit: unit,
          path: path,
          query: query,
          modal: modal,
          animated: animated
        }, function() {
          delete callbacks[cid];
        });
      },
      back: function(animated) {
        if (animated === undefined) {
          animated = true;
        }
        var cid = Efte.send_message('actionBack', {
          animated: animated
        }, function() {
          delete callbacks[cid];
        });
      },
      dismiss: function(animated) {
        if (animated === undefined) {
          animated = true;
        }
        var cid = Efte.send_message('actionDismiss', {
          animated: animated
        }, function() {
          delete callbacks[cid];
        });
      }
    },

    getEnv: function(callback) {
      Efte.send_message('getEnv', {}, function(env) {
        window.AppEnv = window.AppEnv || {
          parseQuery: function() {
            // query not set
            if (this.query == '${query}') {
              this.query = null;
              return;
            }

            var params = {};
            this.query.split('&').forEach(function(param) {
              var kv = param.split('=');
              var k = kv[0];
              var v = kv.length > 0 ? kv[1] : '';
              params[k] = v;
            });

            this.query = params;
          }
        };

        extend(window.AppEnv, env);
        window.AppEnv.parseQuery();

        callback();
      });
    },

    /*
        startRefresh: function() {
            // override this method plz
        },
        */

    stopRefresh: function() {
      Efte.send_message('stopRefresh');
    },
    genUUID: function(id) {
      // buggy
      id = id || AppEnv.dpid;

      // MD5?
      var requid = CryptoJS.MD5(id + (new Date().getTime()) + (Math.random()));
      // console.log(requid.toString());
      return requid.toString();
    },
    setTitle: function(title) {
      var cid = Efte.send_message('setTitle', {
        title: title
      }, function() {
        delete callbacks[cid];
      });
    },
    takePhoto: function(callback) {
      var cid = Efte.send_message('imagePicker', {}, function(result) {
        typeof callback == 'function' && callback(result && result.image);
        delete callbacks[cid];
      });
    },

    // 设置导航栏按钮
    /**
     * [{
     *  title: 'Foo',
     *  action: function () {}
     * }]
     */
    setBarButtons: function(buttons) {
      buttons = isArray(buttons) ? buttons : [buttons];
      var actionFns = [];
      buttons.forEach(function(button) {
        actionFns.push(button.action || emptyFn);
      });
      Efte.send_message('setBarButtons', {
        buttons: buttons
      }, function(result) {
        actionFns[result.index]();
      });
    },

    /* notification publish & subscribe */
    publish: function(name, value) {
      Efte.send_message('publish', {
        name: name,
        value: value
      });
    },

    /* callback(publisher's value); */
    subscribe: function(name, callback) {
      var cid = Efte.send_message('subscribe', {
        name: name
      }, function(result) {
        (typeof callback == 'function') && callback(result.value);
      });
      return {
        unsubscribe: function() {
          delete callbacks[cid];
        }
      }
    }
  };

  try {
    module.exports = Efte;
  } catch (e) {
    window.Efte = Efte;
  }

})();<commit_msg>ajax error callback<commit_after>(function() {

  var callbacksCount = 1;
  var callbacks = {};

  var isArray = Array.isArray || function(obj) {
    return obj instanceof Array;
  };

  var extend = function(obj, source) {
    if (!source) return obj;

    for (var prop in source) {
      if (source[prop] !== undefined)
        obj[prop] = source[prop];
    }

    return obj;
  };

  var noop = function() {}

  var Efte = {

    send_message: function(method, args, callback) {
      // console.log('send_message', arguments);
      var hasCallback = callback && typeof callback == 'function';
      var callbackId = hasCallback ? callbacksCount++ : 0;
      if (hasCallback) callbacks[callbackId] = callback;

      args['callbackId'] = callbackId;
      args = (typeof args === 'object') ? JSON.stringify(args) : args + '';
      var ifr = document.createElement('iframe');
      ifr.style.display = 'none';
      document.body.appendChild(ifr);
      ifr.contentWindow.location.href = 'js://_?method=' + method + '&args=' + encodeURIComponent(args) + '&callbackId=' + callbackId;
      // ifr.parentNode.removeChild(ifr);
      setTimeout(function() {
        ifr.parentNode.removeChild(ifr);
      }, 0);

      return callbackId;
    },

    callback: function(callbackId, retValue) {
      try {
        var callback = callbacks[callbackId];
        if (!callback) return;
        callback.apply(null, [retValue]);
        // delete callbacks[callbackId];
      } catch (e) {
        alert(e);
      }
    },

    ajax: function(opts) {
      var success = opts.success || noop;
      var error = opts.error || noop;

      // null data lead native error
      if (!opts.data) {
        delete opts.data;
      }

      var callbackID = Efte.send_message('ajax', opts, function(json) {
        var errMsg = '';
        if (json.code == 0) {
          var rsp = null;
          try {
            rsp = JSON.parse(json.responseText);
            success(rsp);
            delete callbacks[callbackID];
          } catch (e) {
            error(-2, 'parse json error: ' + e.message);
            console.log(json);
            delete callbacks[callbackID];
          }
        } else {
          error(json.code, json.message);
          delete callbacks[callbackID];
        }
      });
      return {
        cancel: function() {
          delete callbacks[callbackID];
        }
      };
    },

    action: {
      get: function(callback) {
        var cid = Efte.send_message('actionGetQuery', {}, function(query) {
          if (typeof callback != 'function') return;
          callback(query);
          delete callbacks[cid];
        });
      },
      open: function(unit, path, query, modal, animated) {
        modal = !!modal;
        if (animated === undefined) {
          animated = true;
        }
        var cid = Efte.send_message('actionOpen', {
          unit: unit,
          path: path,
          query: query,
          modal: modal,
          animated: animated
        }, function() {
          delete callbacks[cid];
        });
      },
      back: function(animated) {
        if (animated === undefined) {
          animated = true;
        }
        var cid = Efte.send_message('actionBack', {
          animated: animated
        }, function() {
          delete callbacks[cid];
        });
      },
      dismiss: function(animated) {
        if (animated === undefined) {
          animated = true;
        }
        var cid = Efte.send_message('actionDismiss', {
          animated: animated
        }, function() {
          delete callbacks[cid];
        });
      }
    },

    getEnv: function(callback) {
      Efte.send_message('getEnv', {}, function(env) {
        window.AppEnv = window.AppEnv || {
          parseQuery: function() {
            // query not set
            if (this.query == '${query}') {
              this.query = null;
              return;
            }

            var params = {};
            this.query.split('&').forEach(function(param) {
              var kv = param.split('=');
              var k = kv[0];
              var v = kv.length > 0 ? kv[1] : '';
              params[k] = v;
            });

            this.query = params;
          }
        };

        extend(window.AppEnv, env);
        window.AppEnv.parseQuery();

        callback();
      });
    },

    /*
        startRefresh: function() {
            // override this method plz
        },
        */

    stopRefresh: function() {
      Efte.send_message('stopRefresh');
    },
    genUUID: function(id) {
      // buggy
      id = id || AppEnv.dpid;

      // MD5?
      var requid = CryptoJS.MD5(id + (new Date().getTime()) + (Math.random()));
      // console.log(requid.toString());
      return requid.toString();
    },
    setTitle: function(title) {
      var cid = Efte.send_message('setTitle', {
        title: title
      }, function() {
        delete callbacks[cid];
      });
    },
    takePhoto: function(callback) {
      var cid = Efte.send_message('imagePicker', {}, function(result) {
        typeof callback == 'function' && callback(result && result.image);
        delete callbacks[cid];
      });
    },

    // 设置导航栏按钮
    /**
     * [{
     *  title: 'Foo',
     *  action: function () {}
     * }]
     */
    setBarButtons: function(buttons) {
      buttons = isArray(buttons) ? buttons : [buttons];
      var actionFns = [];
      buttons.forEach(function(button) {
        actionFns.push(button.action || noop);
      });
      Efte.send_message('setBarButtons', {
        buttons: buttons
      }, function(result) {
        actionFns[result.index]();
      });
    },

    /* notification publish & subscribe */
    publish: function(name, value) {
      Efte.send_message('publish', {
        name: name,
        value: value
      });
    },

    /* callback(publisher's value); */
    subscribe: function(name, callback) {
      var cid = Efte.send_message('subscribe', {
        name: name
      }, function(result) {
        (typeof callback == 'function') && callback(result.value);
      });
      return {
        unsubscribe: function() {
          delete callbacks[cid];
        }
      }
    }
  };

  try {
    module.exports = Efte;
  } catch (e) {
    window.Efte = Efte;
  }

})();<|endoftext|>


<commit_before>/* eslint no-console: 0 */
'use strict';

const irc = require('irc');

const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;

const client = module.exports.client = new irc.Client(server, user, {
  autoConnect: false,
  autoRejoin: true,
  channels: [channel],
  showErrors: true,
});

client.connect(5, () => {
  if (process.env.NODE_ENV !== 'testing') {
    console.log('[IRC] connected');
  }
});

if (process.env.NODE_ENV !== 'testing') {
  client.on('registered', (message) => {
    console.log('[IRC] registered', message.args[1]);
  });
}

client.on('error', (error) => {
  console.error('[IRC] error', error.mesage);
  console.error(error.stack);
  process.exit(1);
});

module.exports.notify = (b, callback) => {
  const msg = `Jenkins build node-test-pull-request#${b.id} for nodejs/node#${b.pr_id} started`;
  client.notice(channel, msg);
  callback(null);
};
<commit_msg>refactor(irc): use addListener instead of on method<commit_after>/* eslint no-console: 0 */
'use strict';

const irc = require('irc');

const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;

const client = module.exports.client = new irc.Client(server, user, {
  autoConnect: false,
  autoRejoin: true,
  channels: [channel],
  showErrors: true,
});

client.connect(5, () => {
  if (process.env.NODE_ENV !== 'testing') {
    console.log('[IRC] connected');
  }
});

if (process.env.NODE_ENV !== 'testing') {
  client.addListener('registered', (message) => {
    console.log('[IRC] registered', message.args[1]);
  });
}

client.addListener('error', (error) => {
  console.error('[IRC] error', error.mesage);
  console.error(error.stack);
  process.exit(1);
});

module.exports.notify = (b, callback) => {
  const msg = `Jenkins build node-test-pull-request#${b.id} for nodejs/node#${b.pr_id} started`;
  client.notice(channel, msg);
  callback(null);
};
<|endoftext|>


<commit_before>import m from 'mithril';
import models from '../models';
import postgrest from 'mithril-postgrest';
import _ from 'underscore';
import h from '../h';
import userVM from '../vms/user-vm';
import inlineError from './inline-error';
import popNotification from './pop-notification';

const userSettings = {
    controller(args) {
        const user = args.user,
            fields = {
                owner_document: m.prop(user.owner_document),
                country_id: m.prop(user.address.country_id),
                street: m.prop(user.address.street),
                number: m.prop(user.address.number),
                city: m.prop(user.address.city),
                zipcode: m.prop(user.address.zipcode),
                complement: m.prop(user.address.complement),
                neighbourhood: m.prop(user.address.neighbourhood),
                state: m.prop(user.address.state),
                phonenumber: m.prop(user.address.phonenumber),
                name: m.prop(user.name)
            },
            user_id = args.userId,
            error = m.prop(''),
            countries = m.prop(),
            states = m.prop(),
            loader = m.prop(true),
            showSuccess = m.prop(false),
            showError = m.prop(false),
            countriesLoader = postgrest.loader(models.country.getPageOptions()),
            statesLoader = postgrest.loader(models.state.getPageOptions()),
            phoneMask = _.partial(h.mask, '(99) 9999-99999'),
            documentMask = _.partial(h.mask, '999.999.999-99'),
            documentCompanyMask = _.partial(h.mask, '99.999.999/9999-99'),
            zipcodeMask = _.partial(h.mask, '99999-999'),
            isCnpj = m.prop(false),
            setCsrfToken = (xhr) => {
                if (h.authenticityToken()) {
                    xhr.setRequestHeader('X-CSRF-Token', h.authenticityToken());
                }
                return;
            },
            updateUserData = (user_id) => {
                const userData = {
                    country_id: fields.country_id(),
                    address_street: fields.street(),
                    address_number: fields.number(),
                    address_city: fields.city(),
                    address_zip_code: fields.zipcode(),
                    address_complement: fields.complement(),
                    address_state: fields.state(),
                    address_neighbourhood: fields.neighbourhood(),
                    phone_number: fields.phonenumber(),
                    owner_document: fields.owner_document(),
                    name: fields.name()
                };

                return m.request({
                    method: 'PUT',
                    url: `/users/${user_id}.json`,
                    data: {
                        user: userData
                    },
                    config: setCsrfToken
                }).then(() => {
                    showSuccess(true);
                    m.redraw();
                }).catch((err) => {
                    if (_.isArray(err.errors)) {
                        error(err.errors.join('<br>'));
                    } else {
                        error('Erro ao atualizar informações.');
                    }

                    showError(true);
                    m.redraw();
                });
            },
            validateDocument = () => {
                const document = fields.owner_document(),
                    striped = String(document).replace(/[\.|\-|\/]*/g,'');
                let isValid = false, errorMessage = '';

                if (document.length > 14) {
                    return h.validateCnpj(document);
                } else if (document.length > 0) {
                    return h.validateCpf(striped);
                }

                return;
            },
            // TODO: this form validation should be abstracted/merged together with others
            onSubmit = () => {
                if (!validateDocument()) {
                    error('CPF/CNPJ inválido');
                    showError(true);
                } else {
                    updateUserData(user_id);
                }

                return false;
            },
            applyZipcodeMask = _.compose(fields.zipcode, zipcodeMask),
            applyPhoneMask = _.compose(fields.phonenumber, phoneMask),
            applyDocumentMask = (value) => {
                if(value.length > 14) {
                    isCnpj(true);
                    fields.owner_document(documentCompanyMask(value));
                } else  {
                    isCnpj(false);
                    fields.owner_document(documentMask(value));
                }

                return;
            };

        countriesLoader.load().then(countries);
        statesLoader.load().then(states);

        return {
            applyDocumentMask: applyDocumentMask,
            applyZipcodeMask: applyZipcodeMask,
            applyPhoneMask: applyPhoneMask,
            countries: countries,
            states: states,
            fields: fields,
            loader: loader,
            showSuccess: showSuccess,
            showError: showError,
            user: user,
            onSubmit: onSubmit,
            error: error
        };
    },
    view(ctrl, args) {
        let user = ctrl.user,
            fields = ctrl.fields;

        return m('[id=\'settings-tab\']', [
            (ctrl.showSuccess() ? m.component(popNotification, {
                message: 'As suas informações foram atualizadas'
            }) : ''),
            (ctrl.showError() ? m.component(popNotification, {
                message: m.trust(ctrl.error()),
                error: true
            }) : ''),
            m('form.w-form', {
                onsubmit: ctrl.onSubmit
            }, [
                m('div', [
                    m('.w-container',
                        m('.w-col.w-col-10.w-col-push-1',
                            m('.w-form.card.card-terciary.u-marginbottom-20', [
                                m('.fontsize-base.fontweight-semibold',
                                    'Nome'
                                ),
                                m('.w-row.u-marginbottom-20', [
                                    m('.w-col.w-col-6.w-sub-col',
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[id=\'user_name\'][name=\'user[name]\'][type=\'text\']', {
                                            value: fields.name(),
                                            onchange: m.withAttr('value', fields.name)
                                        })
                                    ),
                                    m('.w-col.w-col-6')
                                ]),
                                m('.fontsize-base.fontweight-semibold',
                                    'CPF / CNPJ'
                                ),
                                m('.w-row.u-marginbottom-20', [
                                    m('.w-col.w-col-6.w-sub-col',
                                        m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[data-validate-cpf-cnpj=\'true\'][id=\'user_cpf\'][name=\'user[cpf]\'][type=\'tel\']', {
                                            value: fields.owner_document(),
                                            onchange: m.withAttr('value', ctrl.applyDocumentMask),
                                            onkeyup: m.withAttr('value', ctrl.applyDocumentMask)
                                        })
                                    ),
                                    m('.w-col.w-col-6')
                                ]),
                                m('.divider.u-marginbottom-20'),
                                m('.fontsize-base.fontweight-semibold',
                                    'Endereço'
                                ),
                                m('.fontsize-small.u-marginbottom-20',
                                    'Esse é o endereço que foi informado ao realizar seu último apoio. Se você mudou de endereço, altere aqui e, caso você esteja aguardando alguma recompensa, avise por email ao realizador do projeto apoiado.'
                                ),
                                m('.w-row', [
                                    m('.input.select.optional.user_country.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'País'
                                        ),
                                        m('select.select.optional.w-input.text-field.w-select.positive[id=\'user_country_id\'][name=\'user[country_id]\']', {
                                            onchange: m.withAttr('value', fields.country_id)
                                        }, [
                                            m('option[value=\'\']'),
                                            (!_.isEmpty(ctrl.countries()) ?
                                                _.map(ctrl.countries(), (country) => {
                                                    return m(`option${country.id == fields.country_id() ? '[selected="selected"]' : ''}`, {
                                                            value: country.id
                                                        },
                                                        country.name
                                                    );
                                                })

                                                :
                                                '')
                                        ])
                                    ]),
                                    m('.w-col.w-col-6')
                                ]),
                                m('.w-row', [
                                    m('.input.string.optional.user_address_street.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'Endereço'
                                        ),
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[data-required-in-brazil=\'true\'][id=\'user_address_street\'][name=\'user[address_street]\'][type=\'text\']', {
                                            value: fields.street(),
                                            onchange: m.withAttr('value', fields.street)
                                        }),
                                        m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_street\']',
                                            ' translation missing: pt.simple_form.validation_texts.user.address_street'
                                        )
                                    ]),
                                    m('.w-col.w-col-6',
                                        m('.w-row', [
                                            m('.input.tel.optional.user_address_number.w-col.w-col-6.w-col-small-6.w-col-tiny-6.w-sub-col-middle', [
                                                m('label.field-label',
                                                    'Número'
                                                ),
                                                m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[id=\'user_address_number\'][name=\'user[address_number]\'][type=\'tel\']', {
                                                    value: fields.number(),
                                                    onchange: m.withAttr('value', fields.number)
                                                }),
                                                m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_number\']',
                                                    ' translation missing: pt.simple_form.validation_texts.user.address_number'
                                                )
                                            ]),
                                            m('.input.string.optional.user_address_complement.w-col.w-col-6.w-col-small-6.w-col-tiny-6', [
                                                m('label.field-label',
                                                    'Complemento'
                                                ),
                                                m('input.string.optional.w-input.text-field.w-input.text-field.positive[id=\'user_address_complement\'][name=\'user[address_complement]\'][type=\'text\']', {
                                                    value: fields.complement(),
                                                    onchange: m.withAttr('value', fields.complement)
                                                })
                                            ])
                                        ])
                                    )
                                ]),
                                m('.w-row', [
                                    m('.input.string.optional.user_address_neighbourhood.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'Bairro'
                                        ),
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[id=\'user_address_neighbourhood\'][name=\'user[address_neighbourhood]\'][type=\'text\']', {
                                            value: fields.neighbourhood(),
                                            onchange: m.withAttr('value', fields.neighbourhood)
                                        })
                                    ]),
                                    m('.input.string.optional.user_address_city.w-col.w-col-6', [
                                        m('label.field-label',
                                            'Cidade'
                                        ),
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[data-required-in-brazil=\'true\'][id=\'user_address_city\'][name=\'user[address_city]\'][type=\'text\']', {
                                            value: fields.city(),
                                            onchange: m.withAttr('value', fields.city)
                                        }),
                                        m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_city\']',
                                            ' translation missing: pt.simple_form.validation_texts.user.address_city'
                                        )
                                    ])
                                ]),
                                m('.w-row', [
                                    m('.input.select.optional.user_address_state.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'Estado'
                                        ),
                                        m('select.select.optional.w-input.text-field.w-select.text-field.positive[data-required-in-brazil=\'true\'][id=\'user_address_state\'][name=\'user[address_state]\']', {

                                            onchange: m.withAttr('value', fields.state)
                                        }, [
                                            m('option[value=\'\']'),
                                            (!_.isEmpty(ctrl.states()) ?
                                                _.map(ctrl.states(), (state) => {
                                                    return m(`option[value='${state.acronym}']${state.acronym == fields.state() ? '[selected="selected"]' : ''}`, {
                                                            value: state.acronym
                                                        },
                                                        state.name
                                                    );
                                                })

                                                :
                                                ''),
                                            m('option[value=\'outro / other\']',
                                                'Outro / Other'
                                            )
                                        ]),
                                        m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_state\']',
                                            ' translation missing: pt.simple_form.validation_texts.user.address_state'
                                        )
                                    ]),
                                    m('.w-col.w-col-6',
                                        m('.w-row', [
                                            m('.input.tel.optional.user_address_zip_code.w-col.w-col-6.w-col-small-6.w-col-tiny-6.w-sub-col-middle', [
                                                m('label.field-label',
                                                    'CEP'
                                                ),
                                                m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[data-fixed-mask=\'99999-999\'][data-required-in-brazil=\'true\'][id=\'user_address_zip_code\'][name=\'user[address_zip_code]\'][type=\'tel\']', {
                                                    value: fields.zipcode(),
                                                    onchange: m.withAttr('value', fields.zipcode)
                                                }),
                                                m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_zip_code\']',
                                                    ' translation missing: pt.simple_form.validation_texts.user.address_zip_code'
                                                )
                                            ]),
                                            m('.input.tel.optional.user_phone_number.w-col.w-col-6.w-col-small-6.w-col-tiny-6', [
                                                m('label.field-label',
                                                    'Telefone'
                                                ),
                                                m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[data-fixed-mask=\'(99) 9999-99999\'][data-required-in-brazil=\'true\'][id=\'user_phone_number\'][name=\'user[phone_number]\'][type=\'tel\']', {
                                                    value: fields.phonenumber(),
                                                    onchange: m.withAttr('value', fields.phonenumber),
                                                    onkeyup: m.withAttr('value', (value) => ctrl.applyPhoneMask(value))
                                                })
                                            ])
                                        ])
                                    )
                                ]),
                            ])
                        )
                    ),
                    m('div',
                        m('.w-container',
                            m('.w-row', [
                                m('.w-col.w-col-4.w-col-push-4',
                                    m('input.btn.btn.btn-large[name=\'commit\'][type=\'submit\'][value=\'Salvar\']')
                                ),
                                m('.w-col.w-col-4')
                            ])
                        )
                    )
                ])
            ])
        ]);
    }
};

export default userSettings;
<commit_msg>Orders countries by en name in users dashboard<commit_after>import m from 'mithril';
import models from '../models';
import postgrest from 'mithril-postgrest';
import _ from 'underscore';
import h from '../h';
import userVM from '../vms/user-vm';
import inlineError from './inline-error';
import popNotification from './pop-notification';

const userSettings = {
    controller(args) {
        const user = args.user,
            fields = {
                owner_document: m.prop(user.owner_document),
                country_id: m.prop(user.address.country_id),
                street: m.prop(user.address.street),
                number: m.prop(user.address.number),
                city: m.prop(user.address.city),
                zipcode: m.prop(user.address.zipcode),
                complement: m.prop(user.address.complement),
                neighbourhood: m.prop(user.address.neighbourhood),
                state: m.prop(user.address.state),
                phonenumber: m.prop(user.address.phonenumber),
                name: m.prop(user.name)
            },
            user_id = args.userId,
            error = m.prop(''),
            countries = m.prop(),
            states = m.prop(),
            loader = m.prop(true),
            showSuccess = m.prop(false),
            showError = m.prop(false),
            countriesLoader = postgrest.loader(models.country.getPageOptions()),
            statesLoader = postgrest.loader(models.state.getPageOptions()),
            phoneMask = _.partial(h.mask, '(99) 9999-99999'),
            documentMask = _.partial(h.mask, '999.999.999-99'),
            documentCompanyMask = _.partial(h.mask, '99.999.999/9999-99'),
            zipcodeMask = _.partial(h.mask, '99999-999'),
            isCnpj = m.prop(false),
            setCsrfToken = (xhr) => {
                if (h.authenticityToken()) {
                    xhr.setRequestHeader('X-CSRF-Token', h.authenticityToken());
                }
                return;
            },
            updateUserData = (user_id) => {
                const userData = {
                    country_id: fields.country_id(),
                    address_street: fields.street(),
                    address_number: fields.number(),
                    address_city: fields.city(),
                    address_zip_code: fields.zipcode(),
                    address_complement: fields.complement(),
                    address_state: fields.state(),
                    address_neighbourhood: fields.neighbourhood(),
                    phone_number: fields.phonenumber(),
                    owner_document: fields.owner_document(),
                    name: fields.name()
                };

                return m.request({
                    method: 'PUT',
                    url: `/users/${user_id}.json`,
                    data: {
                        user: userData
                    },
                    config: setCsrfToken
                }).then(() => {
                    showSuccess(true);
                    m.redraw();
                }).catch((err) => {
                    if (_.isArray(err.errors)) {
                        error(err.errors.join('<br>'));
                    } else {
                        error('Erro ao atualizar informações.');
                    }

                    showError(true);
                    m.redraw();
                });
            },
            validateDocument = () => {
                const document = fields.owner_document(),
                    striped = String(document).replace(/[\.|\-|\/]*/g,'');
                let isValid = false, errorMessage = '';

                if (document.length > 14) {
                    return h.validateCnpj(document);
                } else if (document.length > 0) {
                    return h.validateCpf(striped);
                }

                return;
            },
            // TODO: this form validation should be abstracted/merged together with others
            onSubmit = () => {
                if (!validateDocument()) {
                    error('CPF/CNPJ inválido');
                    showError(true);
                } else {
                    updateUserData(user_id);
                }

                return false;
            },
            applyZipcodeMask = _.compose(fields.zipcode, zipcodeMask),
            applyPhoneMask = _.compose(fields.phonenumber, phoneMask),
            applyDocumentMask = (value) => {
                if(value.length > 14) {
                    isCnpj(true);
                    fields.owner_document(documentCompanyMask(value));
                } else  {
                    isCnpj(false);
                    fields.owner_document(documentMask(value));
                }

                return;
            };

        countriesLoader.load().then((data) => countries(_.sortBy(data, 'name_en')));
        statesLoader.load().then(states);

        return {
            applyDocumentMask: applyDocumentMask,
            applyZipcodeMask: applyZipcodeMask,
            applyPhoneMask: applyPhoneMask,
            countries: countries,
            states: states,
            fields: fields,
            loader: loader,
            showSuccess: showSuccess,
            showError: showError,
            user: user,
            onSubmit: onSubmit,
            error: error
        };
    },
    view(ctrl, args) {
        let user = ctrl.user,
            fields = ctrl.fields;

        return m('[id=\'settings-tab\']', [
            (ctrl.showSuccess() ? m.component(popNotification, {
                message: 'As suas informações foram atualizadas'
            }) : ''),
            (ctrl.showError() ? m.component(popNotification, {
                message: m.trust(ctrl.error()),
                error: true
            }) : ''),
            m('form.w-form', {
                onsubmit: ctrl.onSubmit
            }, [
                m('div', [
                    m('.w-container',
                        m('.w-col.w-col-10.w-col-push-1',
                            m('.w-form.card.card-terciary.u-marginbottom-20', [
                                m('.fontsize-base.fontweight-semibold',
                                    'Nome'
                                ),
                                m('.w-row.u-marginbottom-20', [
                                    m('.w-col.w-col-6.w-sub-col',
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[id=\'user_name\'][name=\'user[name]\'][type=\'text\']', {
                                            value: fields.name(),
                                            onchange: m.withAttr('value', fields.name)
                                        })
                                    ),
                                    m('.w-col.w-col-6')
                                ]),
                                m('.fontsize-base.fontweight-semibold',
                                    'CPF / CNPJ'
                                ),
                                m('.w-row.u-marginbottom-20', [
                                    m('.w-col.w-col-6.w-sub-col',
                                        m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[data-validate-cpf-cnpj=\'true\'][id=\'user_cpf\'][name=\'user[cpf]\'][type=\'tel\']', {
                                            value: fields.owner_document(),
                                            onchange: m.withAttr('value', ctrl.applyDocumentMask),
                                            onkeyup: m.withAttr('value', ctrl.applyDocumentMask)
                                        })
                                    ),
                                    m('.w-col.w-col-6')
                                ]),
                                m('.divider.u-marginbottom-20'),
                                m('.fontsize-base.fontweight-semibold',
                                    'Endereço'
                                ),
                                m('.fontsize-small.u-marginbottom-20',
                                    'Esse é o endereço que foi informado ao realizar seu último apoio. Se você mudou de endereço, altere aqui e, caso você esteja aguardando alguma recompensa, avise por email ao realizador do projeto apoiado.'
                                ),
                                m('.w-row', [
                                    m('.input.select.optional.user_country.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'País'
                                        ),
                                        m('select.select.optional.w-input.text-field.w-select.positive[id=\'user_country_id\'][name=\'user[country_id]\']', {
                                            onchange: m.withAttr('value', fields.country_id)
                                        }, [
                                            m('option[value=\'\']'),
                                            (!_.isEmpty(ctrl.countries()) ?
                                                _.map(ctrl.countries(), (country) => {
                                                    return m(`option${country.id == fields.country_id() ? '[selected="selected"]' : ''}`, {
                                                            value: country.id
                                                        },
                                                        country.name_en
                                                    );
                                                })

                                                :
                                                '')
                                        ])
                                    ]),
                                    m('.w-col.w-col-6')
                                ]),
                                m('.w-row', [
                                    m('.input.string.optional.user_address_street.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'Endereço'
                                        ),
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[data-required-in-brazil=\'true\'][id=\'user_address_street\'][name=\'user[address_street]\'][type=\'text\']', {
                                            value: fields.street(),
                                            onchange: m.withAttr('value', fields.street)
                                        }),
                                        m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_street\']',
                                            ' translation missing: pt.simple_form.validation_texts.user.address_street'
                                        )
                                    ]),
                                    m('.w-col.w-col-6',
                                        m('.w-row', [
                                            m('.input.tel.optional.user_address_number.w-col.w-col-6.w-col-small-6.w-col-tiny-6.w-sub-col-middle', [
                                                m('label.field-label',
                                                    'Número'
                                                ),
                                                m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[id=\'user_address_number\'][name=\'user[address_number]\'][type=\'tel\']', {
                                                    value: fields.number(),
                                                    onchange: m.withAttr('value', fields.number)
                                                }),
                                                m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_number\']',
                                                    ' translation missing: pt.simple_form.validation_texts.user.address_number'
                                                )
                                            ]),
                                            m('.input.string.optional.user_address_complement.w-col.w-col-6.w-col-small-6.w-col-tiny-6', [
                                                m('label.field-label',
                                                    'Complemento'
                                                ),
                                                m('input.string.optional.w-input.text-field.w-input.text-field.positive[id=\'user_address_complement\'][name=\'user[address_complement]\'][type=\'text\']', {
                                                    value: fields.complement(),
                                                    onchange: m.withAttr('value', fields.complement)
                                                })
                                            ])
                                        ])
                                    )
                                ]),
                                m('.w-row', [
                                    m('.input.string.optional.user_address_neighbourhood.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'Bairro'
                                        ),
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[id=\'user_address_neighbourhood\'][name=\'user[address_neighbourhood]\'][type=\'text\']', {
                                            value: fields.neighbourhood(),
                                            onchange: m.withAttr('value', fields.neighbourhood)
                                        })
                                    ]),
                                    m('.input.string.optional.user_address_city.w-col.w-col-6', [
                                        m('label.field-label',
                                            'Cidade'
                                        ),
                                        m('input.string.optional.w-input.text-field.w-input.text-field.positive[data-required-in-brazil=\'true\'][id=\'user_address_city\'][name=\'user[address_city]\'][type=\'text\']', {
                                            value: fields.city(),
                                            onchange: m.withAttr('value', fields.city)
                                        }),
                                        m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_city\']',
                                            ' translation missing: pt.simple_form.validation_texts.user.address_city'
                                        )
                                    ])
                                ]),
                                m('.w-row', [
                                    m('.input.select.optional.user_address_state.w-col.w-col-6.w-sub-col', [
                                        m('label.field-label',
                                            'Estado'
                                        ),
                                        m('select.select.optional.w-input.text-field.w-select.text-field.positive[data-required-in-brazil=\'true\'][id=\'user_address_state\'][name=\'user[address_state]\']', {

                                            onchange: m.withAttr('value', fields.state)
                                        }, [
                                            m('option[value=\'\']'),
                                            (!_.isEmpty(ctrl.states()) ?
                                                _.map(ctrl.states(), (state) => {
                                                    return m(`option[value='${state.acronym}']${state.acronym == fields.state() ? '[selected="selected"]' : ''}`, {
                                                            value: state.acronym
                                                        },
                                                        state.name
                                                    );
                                                })

                                                :
                                                ''),
                                            m('option[value=\'outro / other\']',
                                                'Outro / Other'
                                            )
                                        ]),
                                        m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_state\']',
                                            ' translation missing: pt.simple_form.validation_texts.user.address_state'
                                        )
                                    ]),
                                    m('.w-col.w-col-6',
                                        m('.w-row', [
                                            m('.input.tel.optional.user_address_zip_code.w-col.w-col-6.w-col-small-6.w-col-tiny-6.w-sub-col-middle', [
                                                m('label.field-label',
                                                    'CEP'
                                                ),
                                                m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[data-fixed-mask=\'99999-999\'][data-required-in-brazil=\'true\'][id=\'user_address_zip_code\'][name=\'user[address_zip_code]\'][type=\'tel\']', {
                                                    value: fields.zipcode(),
                                                    onchange: m.withAttr('value', fields.zipcode)
                                                }),
                                                m('.fontsize-smaller.text-error.u-marginbottom-20.fa.fa-exclamation-triangle.w-hidden[data-error-for=\'user_address_zip_code\']',
                                                    ' translation missing: pt.simple_form.validation_texts.user.address_zip_code'
                                                )
                                            ]),
                                            m('.input.tel.optional.user_phone_number.w-col.w-col-6.w-col-small-6.w-col-tiny-6', [
                                                m('label.field-label',
                                                    'Telefone'
                                                ),
                                                m('input.string.tel.optional.w-input.text-field.w-input.text-field.positive[data-fixed-mask=\'(99) 9999-99999\'][data-required-in-brazil=\'true\'][id=\'user_phone_number\'][name=\'user[phone_number]\'][type=\'tel\']', {
                                                    value: fields.phonenumber(),
                                                    onchange: m.withAttr('value', fields.phonenumber),
                                                    onkeyup: m.withAttr('value', (value) => ctrl.applyPhoneMask(value))
                                                })
                                            ])
                                        ])
                                    )
                                ]),
                            ])
                        )
                    ),
                    m('div',
                        m('.w-container',
                            m('.w-row', [
                                m('.w-col.w-col-4.w-col-push-4',
                                    m('input.btn.btn.btn-large[name=\'commit\'][type=\'submit\'][value=\'Salvar\']')
                                ),
                                m('.w-col.w-col-4')
                            ])
                        )
                    )
                ])
            ])
        ]);
    }
};

export default userSettings;
<|endoftext|>


<commit_before>/**
 * Patterns autosubmit - automatic submission of forms
 *
 * Copyright 2012-2013 Florian Friesdorf
 * Copyright 2012 Simplon B.V. - Wichert Akkerman
 * Copyright 2013 Marko Durkovic
 * Copyright 2014-2015 Syslab.com GmbH - JC Brand
 */
define([
    "jquery",
    "pat-registry",
    "pat-base",
    "pat-logger",
    "pat-parser",
    "pat-input-change-events",
    "pat-utils"
], function($, registry, Base, logging, Parser, input_change_events, utils) {
    var log = logging.getLogger("autosubmit"),
        parser = new Parser("autosubmit");

    // - 400ms -> 400
    // - 400 -> 400
    // - defocus
    parser.addArgument("delay", "400ms");

    return Base.extend({
        name: "autosubmit",
        trigger: ".pat-autosubmit",
        parser: {
            parse: function($el, opts) {
                var cfg = parser.parse($el, opts);
                if (cfg.delay !== "defocus") {
                    cfg.delay = parseInt(cfg.delay.replace(/[^\d]*/g, ""), 10);
                }
                return cfg;
            }
        },

        init: function() {
            this.options = this.parser.parse(this.$el, arguments[1]);
            input_change_events.setup(this.$el, "autosubmit");
            this.registerListeners();
            this.registerTriggers();
            return this.$el;
        },

        registerListeners: function($el) {
            if (this.$el.is("form")) {
                this.$el.find(".pat-subform").addBack(this.$el).each(function (idx, el) {
                    $(el).on("input-change-delayed.pat-autosubmit", this.onInputChange);
                }.bind(this));
            } else {
                $el.on("input-change-delayed.pat-autosubmit", this.onInputChange);
            }
        },

        registerTriggers: function() {
            var isText = this.$el.is("input:text, input[type=search], textarea");
            if (this.options.delay === "defocus" && !isText) {
                log.error("The defocus delay value makes only sense on text input elements.");
                return this.$el;
            }
            if (this.options.delay === "defocus") {
                this.$el.on("input-defocus.pat-autosubmit", function(ev) {
                    $(ev.target).trigger("input-change-delayed");
                });
            } else if (this.options.delay > 0) {
                this.$el.on("input-change.pat-autosubmit", utils.debounce(function(ev) {
                    $(ev.target).trigger("input-change-delayed");
                }, this.options.delay));
            } else {
                this.$el.on("input-change.pat-autosubmit", function(ev) {
                    $(ev.target).trigger("input-change-delayed");
                });
            }
        },

        destroy: function($el) {
            input_change_events.remove($el, "autosubmit");
            if (this.$el.is("form")) {
                this.$el.find(".pat-subform").addBack(this.$el).each(function (idx, el) {
                    $(el).off(".pat-autosubmit");
                });
            } else {
                $el.off(".pat-autosubmit");
            }
        },

        onInputChange: function(ev) {
            ev.stopPropagation();
            $(this).submit();
            log.debug("triggered by " + ev.type);
        }
    });
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Bugfix. Use the attr<commit_after>/**
 * Patterns autosubmit - automatic submission of forms
 *
 * Copyright 2012-2013 Florian Friesdorf
 * Copyright 2012 Simplon B.V. - Wichert Akkerman
 * Copyright 2013 Marko Durkovic
 * Copyright 2014-2015 Syslab.com GmbH - JC Brand
 */
define([
    "jquery",
    "pat-registry",
    "pat-base",
    "pat-logger",
    "pat-parser",
    "pat-input-change-events",
    "pat-utils"
], function($, registry, Base, logging, Parser, input_change_events, utils) {
    var log = logging.getLogger("autosubmit"),
        parser = new Parser("autosubmit");

    // - 400ms -> 400
    // - 400 -> 400
    // - defocus
    parser.addArgument("delay", "400ms");

    return Base.extend({
        name: "autosubmit",
        trigger: ".pat-autosubmit",
        parser: {
            parse: function($el, opts) {
                var cfg = parser.parse($el, opts);
                if (cfg.delay !== "defocus") {
                    cfg.delay = parseInt(cfg.delay.replace(/[^\d]*/g, ""), 10);
                }
                return cfg;
            }
        },

        init: function() {
            this.options = this.parser.parse(this.$el, arguments[1]);
            input_change_events.setup(this.$el, "autosubmit");
            this.registerListeners();
            this.registerTriggers();
            return this.$el;
        },

        registerListeners: function($el) {
            if (this.$el.is("form")) {
                this.$el.find(".pat-subform").addBack(this.$el).each(function (idx, el) {
                    $(el).on("input-change-delayed.pat-autosubmit", this.onInputChange);
                }.bind(this));
            } else {
                this.$el.on("input-change-delayed.pat-autosubmit", this.onInputChange);
            }
        },

        registerTriggers: function() {
            var isText = this.$el.is("input:text, input[type=search], textarea");
            if (this.options.delay === "defocus" && !isText) {
                log.error("The defocus delay value makes only sense on text input elements.");
                return this.$el;
            }
            if (this.options.delay === "defocus") {
                this.$el.on("input-defocus.pat-autosubmit", function(ev) {
                    $(ev.target).trigger("input-change-delayed");
                });
            } else if (this.options.delay > 0) {
                this.$el.on("input-change.pat-autosubmit", utils.debounce(function(ev) {
                    $(ev.target).trigger("input-change-delayed");
                }, this.options.delay));
            } else {
                this.$el.on("input-change.pat-autosubmit", function(ev) {
                    $(ev.target).trigger("input-change-delayed");
                });
            }
        },

        destroy: function($el) {
            input_change_events.remove($el, "autosubmit");
            if (this.$el.is("form")) {
                this.$el.find(".pat-subform").addBack(this.$el).each(function (idx, el) {
                    $(el).off(".pat-autosubmit");
                });
            } else {
                $el.off(".pat-autosubmit");
            }
        },

        onInputChange: function(ev) {
            ev.stopPropagation();
            $(this).submit();
            log.debug("triggered by " + ev.type);
        }
    });
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>