<commit_before>// TODO: Might add support for "exportImage" custom
//   handler as in "ext-server_opensave.js" (and in savefile.php)

export default {
  name: 'php_savefile',
  init ({ $ }) {
    const svgEditor = this;
    const {
      canvas: svgCanvas
    } = svgEditor;
    /**
     * Get file name out of SVGEdit document title.
     * @returns {string}
     */
    function getFileNameFromTitle () {
      const title = svgCanvas.getDocumentTitle();
      return title.trim();
    }
    const saveSvgAction = './savefile.php';
    svgEditor.setCustomHandlers({
      save (win, data) {
        const svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data,
          filename = getFileNameFromTitle();

        $.post(saveSvgAction, { output_svg: svg, filename });
      }
    });
  }
};
<commit_msg>#104 jquery convert as javascript<commit_after>// TODO: Might add support for "exportImage" custom
//   handler as in "ext-server_opensave.js" (and in savefile.php)

export default {
  name: 'php_savefile',
  init ({ $ }) {
    const svgEditor = this;
    const {
      canvas: svgCanvas
    } = svgEditor;
    /**
     * Get file name out of SVGEdit document title.
     * @returns {string}
     */
    function getFileNameFromTitle () {
      const title = svgCanvas.getDocumentTitle();
      return title.trim();
    }
    const saveSvgAction = './savefile.php';
    svgEditor.setCustomHandlers({
      save (win, data) {
        const svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data,
          filename = getFileNameFromTitle();

        // $.post(saveSvgAction, { output_svg: svg, filename });
        let postData =  { output_svg: svg, filename };
        fetch(saveSvgAction, {
          method: "POST",
          body: JSON.stringify(postData)
        }).then( (res) => {
          return res;
        })
        .catch( (error) => { console.info('error =', error);});
      }
    });
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Groupon, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 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.
 *
 * Neither the name of GROUPON nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT
 * HOLDER OR CONTRIBUTORS 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.
 */

'use strict';

const promisify = require('bluebird').promisify;
const Memcached = require('memcached');

function createClient(options) {
  if (options.client) {
    return options.client;
  }
  const hosts = options.hosts || '127.0.0.1:11211';
  return new Memcached(hosts, options);
}

function normalizeValue(value) {
  return value === false ? null : value;
}

/* Uses anything supporting the memcache protocol */
function MemcachedBackend(options) {
  this.type = 'memcached';
  const client = (this.client = createClient(options));
  this._clientGet = promisify(client.get, { context: client });
  this._clientSet = promisify(client.set, { context: client });
  this._clientDel = promisify(client.del, { context: client });
}
module.exports = MemcachedBackend;

MemcachedBackend.prototype.get = function get(key) {
  return this._clientGet(key).then(normalizeValue);
};

MemcachedBackend.prototype.set = function set(key, value, options) {
  return this._clientSet(key, value, options.expire).then(val => val);
};

MemcachedBackend.prototype.unset = function unset(key) {
  return this._clientDel(key).then(() => undefined);
};

MemcachedBackend.prototype.end = function end() {
  return this.client.end();
};
<commit_msg>chore: feedback addressed<commit_after>/*
 * Copyright (c) 2014, Groupon, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 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.
 *
 * Neither the name of GROUPON nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT
 * HOLDER OR CONTRIBUTORS 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.
 */

'use strict';

const promisify = require('bluebird').promisify;
const Memcached = require('memcached');

const noop = () => undefined;

function createClient(options) {
  if (options.client) {
    return options.client;
  }
  const hosts = options.hosts || '127.0.0.1:11211';
  return new Memcached(hosts, options);
}

function normalizeValue(value) {
  return value === false ? null : value;
}

/* Uses anything supporting the memcache protocol */
function MemcachedBackend(options) {
  this.type = 'memcached';
  const client = (this.client = createClient(options));
  this._clientGet = promisify(client.get, { context: client });
  this._clientSet = promisify(client.set, { context: client });
  this._clientDel = promisify(client.del, { context: client });
}
module.exports = MemcachedBackend;

MemcachedBackend.prototype.get = function get(key) {
  return this._clientGet(key).then(normalizeValue);
};

MemcachedBackend.prototype.set = function set(key, value, options) {
  const constant = () => value;
  return this._clientSet(key, value, options.expire).then(constant);
};

MemcachedBackend.prototype.unset = function unset(key) {
  return this._clientDel(key).then(noop);
};

MemcachedBackend.prototype.end = function end() {
  return this.client.end();
};
<|endoftext|>


<commit_before>'use strict';

/**
* Module to benchmark findAll function
*/
const Benchmark = require('benchmark')
, Utils = require('../utils')
, samplesize = require('lodash.samplesize');

const LARGE_SAMPLE_SIZE = 1500, SMALL_SAMPLE_SIZE = 10;

/**
 * Create sample test data
 *
 * @return {Array}
 */
const createTestData = () => {
  let usernames = []
  , profiles = [];

  for (let i = 1; i < 15000; i++) {
    usernames.push({ username: 'username-' + Math.round(Math.random() * 10000000000) });
    profiles.push({
      email: 'email-' + Math.round(Math.random() * 10000000000),
      amount: (Math.random() * 10000000000),
      userId: i
    });
  }

  return [usernames, profiles];
};

/**
 * Init models with sample data, prepare search sample
 */
const setup = (models, sequelize) => {
  let data = createTestData()
    , usernames = data[0]
    , profiles = data[1];

  return models.user
  .bulkCreate(usernames)
  .then(() => {
    return models.profile.bulkCreate(profiles);
  })
  .then(() => {
    // extract search sample
    let largeSample = samplesize(usernames, LARGE_SAMPLE_SIZE).map((u) => u.username)
      , smallSample = samplesize(usernames, SMALL_SAMPLE_SIZE).map((u) => u.username);

    // clear memory
    profiles = null;
    usernames = null;

    return sequelize.Promise.resolve([largeSample, smallSample]);
  });
};

module.exports = function(models, sequelize) {
  let testPromise = sequelize.Promise.defer()
  , findAllSuite = new Benchmark.Suite('findAll');

  let smallSample, largeSample;

  setup(models, sequelize)
    .spread(function(l, s){
      largeSample = l;
      smallSample = s;

      findAllSuite
      .add({
        defer: true,
        name: 'findAll#' + LARGE_SAMPLE_SIZE,
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: largeSample
            }
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      .add({
        defer: true,
        name: 'findAll#' + LARGE_SAMPLE_SIZE + '#include',
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: largeSample
            },
            include: [{model: models.profile, required: true }]
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      .add({
        defer: true,
        name: 'findAll#' + SMALL_SAMPLE_SIZE,
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: smallSample
            }
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      .add({
        defer: true,
        name: 'findAll#' + SMALL_SAMPLE_SIZE + '#include',
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: smallSample
            },
            include: [{model: models.profile, required: true }]
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      // add listeners
      .on('cycle', function(event) {
        Utils.log(String(event.target)
          + ` (mean ${event.target.times.period}s)`
        );
      })
      .on('complete', function() {
        testPromise.resolve();
      })
      .on('error', function(e) {
        Utils.log('Error : ' + e);
        testPromise.reject(e);
      })
      // run async
      .run({ 'async': true });

    });

  return testPromise.promise;
};
<commit_msg>allow setting LARGE/SMALL sample count via env<commit_after>'use strict';

/**
* Module to benchmark findAll function
*/
const Benchmark = require('benchmark')
, Utils = require('../utils')
, samplesize = require('lodash.samplesize');

const LARGE_SAMPLE_SIZE = process.env.LARGE_SAMPLE_SIZE || 1500
    , SMALL_SAMPLE_SIZE = process.env.SMALL_SAMPLE_SIZE || 10;

/**
 * Create sample test data
 *
 * @return {Array}
 */
const createTestData = () => {
  let usernames = []
  , profiles = [];

  for (let i = 1; i < 15000; i++) {
    usernames.push({ username: 'username-' + Math.round(Math.random() * 10000000000) });
    profiles.push({
      email: 'email-' + Math.round(Math.random() * 10000000000),
      amount: (Math.random() * 10000000000),
      userId: i
    });
  }

  return [usernames, profiles];
};

/**
 * Init models with sample data, prepare search sample
 */
const setup = (models, sequelize) => {
  let data = createTestData()
    , usernames = data[0]
    , profiles = data[1];

  return models.user
  .bulkCreate(usernames)
  .then(() => {
    return models.profile.bulkCreate(profiles);
  })
  .then(() => {
    // extract search sample
    let largeSample = samplesize(usernames, LARGE_SAMPLE_SIZE).map((u) => u.username)
      , smallSample = samplesize(usernames, SMALL_SAMPLE_SIZE).map((u) => u.username);

    // clear memory
    profiles = null;
    usernames = null;

    return sequelize.Promise.resolve([largeSample, smallSample]);
  });
};

module.exports = function(models, sequelize) {
  let testPromise = sequelize.Promise.defer()
  , findAllSuite = new Benchmark.Suite('findAll');

  let smallSample, largeSample;

  setup(models, sequelize)
    .spread(function(l, s){
      largeSample = l;
      smallSample = s;

      findAllSuite
      .add({
        defer: true,
        name: 'findAll#' + LARGE_SAMPLE_SIZE,
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: largeSample
            }
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      .add({
        defer: true,
        name: 'findAll#' + LARGE_SAMPLE_SIZE + '#include',
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: largeSample
            },
            include: [{model: models.profile, required: true }]
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      .add({
        defer: true,
        name: 'findAll#' + SMALL_SAMPLE_SIZE,
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: smallSample
            }
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      .add({
        defer: true,
        name: 'findAll#' + SMALL_SAMPLE_SIZE + '#include',
        fn: function(deferred) {
          models.user.findAll({
            where: {
              username: smallSample
            },
            include: [{model: models.profile, required: true }]
          }).then(() => {
            deferred.resolve();
          });
        }
      })
      // add listeners
      .on('cycle', function(event) {
        Utils.log(String(event.target)
          + ` (mean ${event.target.times.period}s)`
        );
      })
      .on('complete', function() {
        testPromise.resolve();
      })
      .on('error', function(e) {
        Utils.log('Error : ' + e);
        testPromise.reject(e);
      })
      // run async
      .run({ 'async': true });

    });

  return testPromise.promise;
};
<|endoftext|>


<commit_before>/**
 * @author Nadim Basalamah <dimbslmh@gmail.com>
 * @version: v1.0.0
 * https://github.com/dimbslmh/bootstrap-table/tree/master/src/extensions/multiple-sort/bootstrap-table-multiple-sort.js
 */

(function($) {
    'use strict';

    var isSingleSort = false;

    var sort_order = {
        asc: 'Ascending',
        desc: 'Descending'
    };

    var showSortModal = function(that) {
        var _selector = that.$sortModal.selector,
            _id = _selector.substr(1);

        if (!$(_id).hasClass("modal")) {
            var sModal = '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
            sModal += '
' + that.options.formatMultipleSort() + '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                     <button id="add" type="button" class="btn btn-default"> ' + that.options.formatAddLevel() + '</button>';
            sModal += '                                     <button id="delete" type="button" class="btn btn-default" disabled> ' + that.options.formatDeleteLevel() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                         	';
            sModal += '
' + that.options.formatColumn() + '
	';
            sModal += '
' + that.options.formatOrder() + '
	';
            sModal += '
';
            sModal += '
';
            sModal += '

';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="btn btn-default" data-dismiss="modal">' + that.options.formatCancel() + '</button>';
            sModal += '                     <button type="button" class="btn btn-primary">' + that.options.formatSort() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';

            $("body").append($(sModal));

            that.$sortModal = $(_selector);
            var $rows = that.$sortModal.find("tbody > tr");

            that.$sortModal.off('click', '#add').on('click', '#add', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current < total) {
                    current++;
                    that.addLevel();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '#delete').on('click', '#delete', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current > 1 && current <= total) {
                    current--;
                    that.$sortModal.find('tbody tr:last').remove();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '.btn-primary').on('click', '.btn-primary', function() {
                var $rows = that.$sortModal.find("tbody > tr"),
                    $alert = that.$sortModal.find('div.alert'),
                    fields = [],
                    results = [];

                that.options.sortPriority = $.map($rows, function(row) {
                    var $row = $(row),
                        name = $row.find('.multi-sort-name').val(),
                        order = $row.find('.multi-sort-order').val();

                    fields.push(name);

                    return {
                        sortName: name,
                        sortOrder: order
                    };
                });

                var sorted_fields = fields.sort();

                for (var i = 0; i < fields.length - 1; i++) {
                    if (sorted_fields[i + 1] == sorted_fields[i]) {
                        results.push(sorted_fields[i]);
                    }
                }

                if (results.length > 0) {
                    if ($alert.length === 0) {
                        $alert = '
' + that.options.formatDuplicateAlertTitle() + ' ' + that.options.formatDuplicateAlertDescription() + '
';
                        $($alert).insertBefore(that.$sortModal.find('.bars'));
                    }
                } else {
                    if ($alert.length === 1) {
                        $($alert).remove();
                    }

                    that.options.sortName = "";
                    that.onMultipleSort();
                    that.$sortModal.modal('hide');
                }
            });

            if (that.options.sortPriority === null || that.options.sortPriority.length === 0) {
                if (that.options.sortName) {
                    that.options.sortPriority = [{
                        sortName: that.options.sortName,
                        sortOrder: that.options.sortOrder
                    }];
                }
            }

            if (that.options.sortPriority !== null && that.options.sortPriority.length > 0) {
                if ($rows.length < that.options.sortPriority.length && typeof that.options.sortPriority === 'object') {
                    for (var i = 0; i < that.options.sortPriority.length; i++) {
                        that.addLevel(i, that.options.sortPriority[i]);
                    }
                }
            } else {
                that.addLevel(0);
            }

            that.setButtonStates();
        }
    };

    $.extend($.fn.bootstrapTable.defaults, {
        showMultiSort: false,
        sortPriority: null,
        onMultipleSort: function() {
            return false;
        }
    });

    $.extend($.fn.bootstrapTable.defaults.icons, {
        sort: 'glyphicon-sort',
        plus: 'glyphicon-plus',
        minus: 'glyphicon-minus'
    });

    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
        'multiple-sort.bs.table': 'onMultipleSort'
    });

    $.extend($.fn.bootstrapTable.locales, {
        formatMultipleSort: function() {
            return 'Multiple Sort';
        },
        formatAddLevel: function() {
            return "Add Level";
        },
        formatDeleteLevel: function() {
            return "Delete Level";
        },
        formatColumn: function() {
            return "Column";
        },
        formatOrder: function() {
            return "Order";
        },
        formatSortBy: function() {
            return "Sort by";
        },
        formatThenBy: function() {
            return "Then by";
        },
        formatSort: function() {
            return "Sort";
        },
        formatCancel: function() {
            return "Cancel";
        },
        formatDuplicateAlertTitle: function() {
            return "Duplicate(s) detected!";
        },
        formatDuplicateAlertDescription: function() {
            return "Please remove or change any duplicate column.";
        }
    });

    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);

    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _initToolbar = BootstrapTable.prototype.initToolbar;

    BootstrapTable.prototype.initToolbar = function() {
        this.showToolbar = true;
        var that = this,
            sortModalId = '#sortModal_' + this.$el.attr('id');
        this.$sortModal = $(sortModalId);

        _initToolbar.apply(this, Array.prototype.slice.apply(arguments));

        if (this.options.showMultiSort) {
            var $btnGroup = this.$toolbar.find('>.btn-group'),
                $multiSortBtn = $btnGroup.find('div.multi-sort');

            if (!$multiSortBtn.length) {
                $multiSortBtn = '  <button class="multi-sort btn btn-default' + (this.options.iconSize === undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" data-toggle="modal" data-target="' + sortModalId + '" title="' + this.options.formatMultipleSort() + '">';
                $multiSortBtn += '     ';
                $multiSortBtn += '</button>';

                $btnGroup.append($multiSortBtn);

                showSortModal(that);
            }

            this.$el.on('sort.bs.table', function() {
                isSingleSort = true;
            });

            this.$el.on('multiple-sort.bs.table', function() {
                isSingleSort = false;
            });

            this.$el.on('load-success.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.onMultipleSort();
                }
            });

            this.$el.on('column-switch.bs.table', function(field, checked) {
                for (var i = 0; i < that.options.sortPriority.length; i++) {
                    if (that.options.sortPriority[i].sortName === checked) {
                        that.options.sortPriority.splice(i, 1);
                    }
                }

                that.assignSortableArrows();
                that.$sortModal.remove();
                showSortModal(that);
            });

            this.$el.on('reset-view.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.assignSortableArrows();
                }
            });
        }
    };

    BootstrapTable.prototype.onMultipleSort = function() {
        var that = this;

        var cmp = function(x, y) {
            return x > y ? 1 : x < y ? -1 : 0;
        };

        var arrayCmp = function(a, b) {
            var arr1 = [],
                arr2 = [];

            for (var i = 0; i < that.options.sortPriority.length; i++) {
                var order = that.options.sortPriority[i].sortOrder === 'desc' ? -1 : 1,
                    aa = a[that.options.sortPriority[i].sortName],
                    bb = b[that.options.sortPriority[i].sortName];

                if (aa === undefined || aa === null) {
                    aa = '';
                }
                if (bb === undefined || bb === null) {
                    bb = '';
                }
                if ($.isNumeric(aa) && $.isNumeric(bb)) {
                    aa = parseFloat(aa);
                    bb = parseFloat(bb);
                }
                if (typeof aa !== 'string') {
                    aa = aa.toString();
                }

                arr1.push(
                    order * cmp(aa, bb));
                arr2.push(
                    order * cmp(bb, aa));
            }

            return cmp(arr1, arr2);
        };

        this.data.sort(function(a, b) {
            return arrayCmp(a, b);
        });

        this.initBody();
        this.assignSortableArrows();
        this.trigger('multiple-sort');
    };

    BootstrapTable.prototype.addLevel = function(index, sortPriority) {
        var text = index === 0 ? this.options.formatSortBy() : this.options.formatThenBy();

        this.$sortModal.find('tbody')
            .append($('
')
                .append($('').text(text))
                .append($('').append($('<select class="form-control multi-sort-name">')))
                .append($('').append($('<select class="form-control multi-sort-order">')))
        );

        var $multiSortName = this.$sortModal.find('.multi-sort-name').last(),
            $multiSortOrder = this.$sortModal.find('.multi-sort-order').last();

        this.options.columns.forEach(function(column) {
            if (column.sortable === false || column.visible === false) {
                return true;
            }
            $multiSortName.append('<option value="' + column.field + '">' + column.title + '</option>');
        });

        $.each(sort_order, function(value, order) {
            $multiSortOrder.append('<option value="' + value + '">' + order + '</option>');
        });

        if (sortPriority !== undefined) {
            $multiSortName.find('option[value="' + sortPriority.sortName + '"]').attr("selected", true);
            $multiSortOrder.find('option[value="' + sortPriority.sortOrder + '"]').attr("selected", true);
        }
    };

    BootstrapTable.prototype.assignSortableArrows = function() {
        var that = this,
            headers = that.$header.find('th');

        for (var i = 0; i < headers.length; i++) {
            for (var c = 0; c < that.options.sortPriority.length; c++) {
                if ($(headers[i]).data('field') === that.options.sortPriority[c].sortName) {
                    $(headers[i]).find('.sortable').removeClass('desc asc').addClass(that.options.sortPriority[c].sortOrder);
                }
            }
        }
    };

    BootstrapTable.prototype.setButtonStates = function() {
        var total = this.$sortModal.find('.multi-sort-name:first option').length,
            current = this.$sortModal.find('tbody tr').length;

        if (current == total) {
            this.$sortModal.find('#add').attr('disabled', 'disabled');
        }
        if (current > 1) {
            this.$sortModal.find('#delete').removeAttr('disabled');
        }
        if (current < total) {
            this.$sortModal.find('#add').removeAttr('disabled');
        }
        if (current == 1) {
            this.$sortModal.find('#delete').attr('disabled', 'disabled');
        }
    };
})(jQuery);<commit_msg>Fixes issue #1055<commit_after>/**
 * @author Nadim Basalamah <dimbslmh@gmail.com>
 * @version: v1.0.0
 * https://github.com/dimbslmh/bootstrap-table/tree/master/src/extensions/multiple-sort/bootstrap-table-multiple-sort.js
 */

(function($) {
    'use strict';

    var isSingleSort = false;

    var sort_order = {
        asc: 'Ascending',
        desc: 'Descending'
    };

    var showSortModal = function(that) {
        var _selector = that.$sortModal.selector,
            _id = _selector.substr(1);

        if (!$(_id).hasClass("modal")) {
            var sModal = '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
            sModal += '
' + that.options.formatMultipleSort() + '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                     <button id="add" type="button" class="btn btn-default"> ' + that.options.formatAddLevel() + '</button>';
            sModal += '                                     <button id="delete" type="button" class="btn btn-default" disabled> ' + that.options.formatDeleteLevel() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                         	';
            sModal += '
' + that.options.formatColumn() + '
	';
            sModal += '
' + that.options.formatOrder() + '
	';
            sModal += '
';
            sModal += '
';
            sModal += '

';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="btn btn-default" data-dismiss="modal">' + that.options.formatCancel() + '</button>';
            sModal += '                     <button type="button" class="btn btn-primary">' + that.options.formatSort() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';

            $("body").append($(sModal));

            that.$sortModal = $(_selector);
            var $rows = that.$sortModal.find("tbody > tr");

            that.$sortModal.off('click', '#add').on('click', '#add', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current < total) {
                    current++;
                    that.addLevel();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '#delete').on('click', '#delete', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current > 1 && current <= total) {
                    current--;
                    that.$sortModal.find('tbody tr:last').remove();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '.btn-primary').on('click', '.btn-primary', function() {
                var $rows = that.$sortModal.find("tbody > tr"),
                    $alert = that.$sortModal.find('div.alert'),
                    fields = [],
                    results = [];

                that.options.sortPriority = $.map($rows, function(row) {
                    var $row = $(row),
                        name = $row.find('.multi-sort-name').val(),
                        order = $row.find('.multi-sort-order').val();

                    fields.push(name);

                    return {
                        sortName: name,
                        sortOrder: order
                    };
                });

                var sorted_fields = fields.sort();

                for (var i = 0; i < fields.length - 1; i++) {
                    if (sorted_fields[i + 1] == sorted_fields[i]) {
                        results.push(sorted_fields[i]);
                    }
                }

                if (results.length > 0) {
                    if ($alert.length === 0) {
                        $alert = '
' + that.options.formatDuplicateAlertTitle() + ' ' + that.options.formatDuplicateAlertDescription() + '
';
                        $($alert).insertBefore(that.$sortModal.find('.bars'));
                    }
                } else {
                    if ($alert.length === 1) {
                        $($alert).remove();
                    }

                    that.options.sortName = "";
                    that.onMultipleSort();
                    that.$sortModal.modal('hide');
                }
            });

            if (that.options.sortPriority === null || that.options.sortPriority.length === 0) {
                if (that.options.sortName) {
                    that.options.sortPriority = [{
                        sortName: that.options.sortName,
                        sortOrder: that.options.sortOrder
                    }];
                }
            }

            if (that.options.sortPriority !== null && that.options.sortPriority.length > 0) {
                if ($rows.length < that.options.sortPriority.length && typeof that.options.sortPriority === 'object') {
                    for (var i = 0; i < that.options.sortPriority.length; i++) {
                        that.addLevel(i, that.options.sortPriority[i]);
                    }
                }
            } else {
                that.addLevel(0);
            }

            that.setButtonStates();
        }
    };

    $.extend($.fn.bootstrapTable.defaults, {
        showMultiSort: false,
        sortPriority: null,
        onMultipleSort: function() {
            return false;
        }
    });

    $.extend($.fn.bootstrapTable.defaults.icons, {
        sort: 'glyphicon-sort',
        plus: 'glyphicon-plus',
        minus: 'glyphicon-minus'
    });

    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
        'multiple-sort.bs.table': 'onMultipleSort'
    });

    $.extend($.fn.bootstrapTable.locales, {
        formatMultipleSort: function() {
            return 'Multiple Sort';
        },
        formatAddLevel: function() {
            return "Add Level";
        },
        formatDeleteLevel: function() {
            return "Delete Level";
        },
        formatColumn: function() {
            return "Column";
        },
        formatOrder: function() {
            return "Order";
        },
        formatSortBy: function() {
            return "Sort by";
        },
        formatThenBy: function() {
            return "Then by";
        },
        formatSort: function() {
            return "Sort";
        },
        formatCancel: function() {
            return "Cancel";
        },
        formatDuplicateAlertTitle: function() {
            return "Duplicate(s) detected!";
        },
        formatDuplicateAlertDescription: function() {
            return "Please remove or change any duplicate column.";
        }
    });

    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);

    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _initToolbar = BootstrapTable.prototype.initToolbar;

    BootstrapTable.prototype.initToolbar = function() {
        this.showToolbar = true;
        var that = this,
            sortModalId = '#sortModal_' + this.$el.attr('id');
        this.$sortModal = $(sortModalId);

        _initToolbar.apply(this, Array.prototype.slice.apply(arguments));

        if (this.options.showMultiSort) {
            var $btnGroup = this.$toolbar.find('>.btn-group').first(),
                $multiSortBtn = this.$toolbar.find('div.multi-sort');

            if (!$multiSortBtn.length) {
                $multiSortBtn = '  <button class="multi-sort btn btn-default' + (this.options.iconSize === undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" data-toggle="modal" data-target="' + sortModalId + '" title="' + this.options.formatMultipleSort() + '">';
                $multiSortBtn += '     ';
                $multiSortBtn += '</button>';

                $btnGroup.append($multiSortBtn);

                showSortModal(that);
            }

            this.$el.on('sort.bs.table', function() {
                isSingleSort = true;
            });

            this.$el.on('multiple-sort.bs.table', function() {
                isSingleSort = false;
            });

            this.$el.on('load-success.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.onMultipleSort();
                }
            });

            this.$el.on('column-switch.bs.table', function(field, checked) {
                for (var i = 0; i < that.options.sortPriority.length; i++) {
                    if (that.options.sortPriority[i].sortName === checked) {
                        that.options.sortPriority.splice(i, 1);
                    }
                }

                that.assignSortableArrows();
                that.$sortModal.remove();
                showSortModal(that);
            });

            this.$el.on('reset-view.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.assignSortableArrows();
                }
            });
        }
    };

    BootstrapTable.prototype.onMultipleSort = function() {
        var that = this;

        var cmp = function(x, y) {
            return x > y ? 1 : x < y ? -1 : 0;
        };

        var arrayCmp = function(a, b) {
            var arr1 = [],
                arr2 = [];

            for (var i = 0; i < that.options.sortPriority.length; i++) {
                var order = that.options.sortPriority[i].sortOrder === 'desc' ? -1 : 1,
                    aa = a[that.options.sortPriority[i].sortName],
                    bb = b[that.options.sortPriority[i].sortName];

                if (aa === undefined || aa === null) {
                    aa = '';
                }
                if (bb === undefined || bb === null) {
                    bb = '';
                }
                if ($.isNumeric(aa) && $.isNumeric(bb)) {
                    aa = parseFloat(aa);
                    bb = parseFloat(bb);
                }
                if (typeof aa !== 'string') {
                    aa = aa.toString();
                }

                arr1.push(
                    order * cmp(aa, bb));
                arr2.push(
                    order * cmp(bb, aa));
            }

            return cmp(arr1, arr2);
        };

        this.data.sort(function(a, b) {
            return arrayCmp(a, b);
        });

        this.initBody();
        this.assignSortableArrows();
        this.trigger('multiple-sort');
    };

    BootstrapTable.prototype.addLevel = function(index, sortPriority) {
        var text = index === 0 ? this.options.formatSortBy() : this.options.formatThenBy();

        this.$sortModal.find('tbody')
            .append($('
')
                .append($('').text(text))
                .append($('').append($('<select class="form-control multi-sort-name">')))
                .append($('').append($('<select class="form-control multi-sort-order">')))
        );

        var $multiSortName = this.$sortModal.find('.multi-sort-name').last(),
            $multiSortOrder = this.$sortModal.find('.multi-sort-order').last();

        this.options.columns.forEach(function(column) {
            if (column.sortable === false || column.visible === false) {
                return true;
            }
            $multiSortName.append('<option value="' + column.field + '">' + column.title + '</option>');
        });

        $.each(sort_order, function(value, order) {
            $multiSortOrder.append('<option value="' + value + '">' + order + '</option>');
        });

        if (sortPriority !== undefined) {
            $multiSortName.find('option[value="' + sortPriority.sortName + '"]').attr("selected", true);
            $multiSortOrder.find('option[value="' + sortPriority.sortOrder + '"]').attr("selected", true);
        }
    };

    BootstrapTable.prototype.assignSortableArrows = function() {
        var that = this,
            headers = that.$header.find('th');

        for (var i = 0; i < headers.length; i++) {
            for (var c = 0; c < that.options.sortPriority.length; c++) {
                if ($(headers[i]).data('field') === that.options.sortPriority[c].sortName) {
                    $(headers[i]).find('.sortable').removeClass('desc asc').addClass(that.options.sortPriority[c].sortOrder);
                }
            }
        }
    };

    BootstrapTable.prototype.setButtonStates = function() {
        var total = this.$sortModal.find('.multi-sort-name:first option').length,
            current = this.$sortModal.find('tbody tr').length;

        if (current == total) {
            this.$sortModal.find('#add').attr('disabled', 'disabled');
        }
        if (current > 1) {
            this.$sortModal.find('#delete').removeAttr('disabled');
        }
        if (current < total) {
            this.$sortModal.find('#add').removeAttr('disabled');
        }
        if (current == 1) {
            this.$sortModal.find('#delete').attr('disabled', 'disabled');
        }
    };
})(jQuery);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, Groupon, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 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.
 *
 * Neither the name of GROUPON nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT
 * HOLDER OR CONTRIBUTORS 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.
 */

'use strict';

const assert = require('assertive');
const isEmpty = require('lodash/isEmpty');

function getTotalScore(success, failure) {
  const successCount = Object.keys(success).length;
  const errorCount = Object.keys(failure).length;

  return (successCount * 100) / (successCount + errorCount);
}

const lhConfig = {
  passes: [
    {
      passName: 'accessibilityPass',
      gatherers: ['accessibility'],
    },
  ],
  audits: [
    'accessibility/accesskeys',
    'accessibility/aria-allowed-attr',
    'accessibility/aria-required-attr',
    'accessibility/aria-required-children',
    'accessibility/aria-required-parent',
    'accessibility/aria-roles',
    'accessibility/aria-valid-attr-value',
    'accessibility/aria-valid-attr',
    'accessibility/audio-caption',
    'accessibility/button-name',
    'accessibility/bypass',
    'accessibility/color-contrast',
    'accessibility/definition-list',
    'accessibility/dlitem',
    'accessibility/document-title',
    'accessibility/duplicate-id',
    'accessibility/frame-title',
    'accessibility/html-has-lang',
    'accessibility/html-lang-valid',
    'accessibility/image-alt',
    'accessibility/input-image-alt',
    'accessibility/label',
    'accessibility/layout-table',
    'accessibility/link-name',
    'accessibility/list',
    'accessibility/listitem',
    'accessibility/meta-refresh',
    'accessibility/meta-viewport',
    'accessibility/object-alt',
    'accessibility/tabindex',
    'accessibility/td-headers-attr',
    'accessibility/th-has-data-cells',
    'accessibility/valid-lang',
    'accessibility/video-caption',
    'accessibility/video-description',
  ],
};

const parseLhResult = function(results) {
  if (!results || !results.lhr || !results.lhr.audits) {
    throw new Error(`Error fetching lighthouse audit results`);
  }

  const audits = results.lhr.audits;

  const errorsObj = {};
  const notApplicableObj = {};
  const successObj = {};

  for (const key in audits) {
    const audit = audits[key];
    const description = audit.description;
    const details = audit.details;
    const id = audit.id;
    const score = audit.score;
    const scoreDisplayMode = audit.scoreDisplayMode;

    const auditInfo = { description, details };

    if (score) {
      successObj[id] = auditInfo;
    } else if (scoreDisplayMode === 'not-applicable') {
      notApplicableObj[id] = auditInfo;
    } else if (scoreDisplayMode !== 'manual') {
      const snippets = [];
      if (!isEmpty(details.items)) {
        details.items.forEach(item => snippets.push(item.node.snippet || ''));
      }

      errorsObj[id] = { description, snippets };
    }
  }

  const score = getTotalScore(successObj, errorsObj);

  return {
    audits,
    score,
    isSuccess(cutoff) {
      return score >= cutoff;
    },
    success(type) {
      return type ? successObj[type] : successObj;
    },
    errors(type) {
      return type ? errorsObj[type] : errorsObj;
    },
    errorString() {
      const errorList = [];

      for (const id in errorsObj) {
        const description = errorsObj[id].description;
        const snippets = errorsObj[id].snippets;
        errorList.push(`${description}:\n\t${snippets.join('\n\t')}`);
      }

      return errorList.join('\n\n');
    },
  };
};

exports.assertLighthouseScore = function assertLighthouseScore(
  score,
  flags,
  config
) {
  const assertScore = function aScore(res) {
    assert.expect(parseLhResult(res).isSuccess(score));
  };

  return this.getLighthouseData(flags, config || lhConfig).then(assertScore);
};

exports.runLighthouseAudit = function runLighthouseAudit(flags, config) {
  return this.getLighthouseData(flags, config || lhConfig).then(parseLhResult);
};
<commit_msg>fix: path change of accessibility audit<commit_after>/*
 * Copyright (c) 2015, Groupon, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 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.
 *
 * Neither the name of GROUPON nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT
 * HOLDER OR CONTRIBUTORS 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.
 */

'use strict';

const assert = require('assertive');
const isEmpty = require('lodash/isEmpty');

function getTotalScore(success, failure) {
  const successCount = Object.keys(success).length;
  const errorCount = Object.keys(failure).length;

  return (successCount * 100) / (successCount + errorCount);
}

const lhConfig = {
  passes: [
    {
      passName: 'accessibilityPass',
      gatherers: ['accessibility'],
    },
  ],
  audits: [
    'accessibility/manual/accesskeys',
    'accessibility/aria-allowed-attr',
    'accessibility/aria-required-attr',
    'accessibility/aria-required-children',
    'accessibility/aria-required-parent',
    'accessibility/aria-roles',
    'accessibility/aria-valid-attr-value',
    'accessibility/aria-valid-attr',
    'accessibility/audio-caption',
    'accessibility/button-name',
    'accessibility/bypass',
    'accessibility/color-contrast',
    'accessibility/definition-list',
    'accessibility/dlitem',
    'accessibility/document-title',
    'accessibility/duplicate-id',
    'accessibility/frame-title',
    'accessibility/html-has-lang',
    'accessibility/html-lang-valid',
    'accessibility/image-alt',
    'accessibility/input-image-alt',
    'accessibility/label',
    'accessibility/layout-table',
    'accessibility/link-name',
    'accessibility/list',
    'accessibility/listitem',
    'accessibility/meta-refresh',
    'accessibility/meta-viewport',
    'accessibility/object-alt',
    'accessibility/tabindex',
    'accessibility/td-headers-attr',
    'accessibility/th-has-data-cells',
    'accessibility/valid-lang',
    'accessibility/video-caption',
    'accessibility/video-description',
  ],
};

const parseLhResult = function(results) {
  if (!results || !results.lhr || !results.lhr.audits) {
    throw new Error(`Error fetching lighthouse audit results`);
  }

  const audits = results.lhr.audits;

  const errorsObj = {};
  const notApplicableObj = {};
  const successObj = {};

  for (const key in audits) {
    const audit = audits[key];
    const description = audit.description;
    const details = audit.details;
    const id = audit.id;
    const score = audit.score;
    const scoreDisplayMode = audit.scoreDisplayMode;

    const auditInfo = { description, details };

    if (score) {
      successObj[id] = auditInfo;
    } else if (scoreDisplayMode === 'not-applicable') {
      notApplicableObj[id] = auditInfo;
    } else if (scoreDisplayMode !== 'manual') {
      const snippets = [];
      if (!isEmpty(details.items)) {
        details.items.forEach(item => snippets.push(item.node.snippet || ''));
      }

      errorsObj[id] = { description, snippets };
    }
  }

  const score = getTotalScore(successObj, errorsObj);

  return {
    audits,
    score,
    isSuccess(cutoff) {
      return score >= cutoff;
    },
    success(type) {
      return type ? successObj[type] : successObj;
    },
    errors(type) {
      return type ? errorsObj[type] : errorsObj;
    },
    errorString() {
      const errorList = [];

      for (const id in errorsObj) {
        const description = errorsObj[id].description;
        const snippets = errorsObj[id].snippets;
        errorList.push(`${description}:\n\t${snippets.join('\n\t')}`);
      }

      return errorList.join('\n\n');
    },
  };
};

exports.assertLighthouseScore = function assertLighthouseScore(
  score,
  flags,
  config
) {
  const assertScore = function aScore(res) {
    assert.expect(parseLhResult(res).isSuccess(score));
  };

  return this.getLighthouseData(flags, config || lhConfig).then(assertScore);
};

exports.runLighthouseAudit = function runLighthouseAudit(flags, config) {
  return this.getLighthouseData(flags, config || lhConfig).then(parseLhResult);
};
<|endoftext|>


<commit_before>/**
 * @author Nadim Basalamah <dimbslmh@gmail.com>
 * @version: v1.0.0
 * https://github.com/dimbslmh/bootstrap-table/tree/master/src/extensions/multiple-sort/bootstrap-table-multiple-sort.js
 */

(function($) {
    'use strict';

    var isSingleSort = false;

    var sort_order = {
        asc: 'Ascending',
        desc: 'Descending'
    };

    var showSortModal = function(that) {
        var _selector = that.$sortModal.selector,
            _id = _selector.substr(1);

        if (!$(_id).hasClass("modal")) {
            var sModal = '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
            sModal += '
' + that.options.formatMultipleSort() + '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                     <button id="add" type="button" class="btn btn-default"> ' + that.options.formatAddLevel() + '</button>';
            sModal += '                                     <button id="delete" type="button" class="btn btn-default" disabled> ' + that.options.formatDeleteLevel() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                         	';
            sModal += '
' + that.options.formatColumn() + '
	';
            sModal += '
' + that.options.formatOrder() + '
	';
            sModal += '
';
            sModal += '
';
            sModal += '

';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="btn btn-default" data-dismiss="modal">' + that.options.formatCancel() + '</button>';
            sModal += '                     <button type="button" class="btn btn-primary">' + that.options.formatSort() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';

            $("body").append($(sModal));

            that.$sortModal = $(_selector);
            var $rows = that.$sortModal.find("tbody > tr");

            that.$sortModal.off('click', '#add').on('click', '#add', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current < total) {
                    current++;
                    that.addLevel();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '#delete').on('click', '#delete', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current > 1 && current <= total) {
                    current--;
                    that.$sortModal.find('tbody tr:last').remove();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '.btn-primary').on('click', '.btn-primary', function() {
                var $rows = that.$sortModal.find("tbody > tr"),
                    $alert = that.$sortModal.find('div.alert'),
                    fields = [],
                    results = [];

                that.options.sortPriority = $.map($rows, function(row) {
                    var $row = $(row),
                        name = $row.find('.multi-sort-name').val(),
                        order = $row.find('.multi-sort-order').val();

                    fields.push(name);

                    return {
                        sortName: name,
                        sortOrder: order
                    };
                });

                var sorted_fields = fields.sort();

                for (var i = 0; i < fields.length - 1; i++) {
                    if (sorted_fields[i + 1] == sorted_fields[i]) {
                        results.push(sorted_fields[i]);
                    }
                }

                if (results.length > 0) {
                    if ($alert.length === 0) {
                        $alert = '
' + that.options.formatDuplicateAlertTitle() + ' ' + that.options.formatDuplicateAlertDescription() + '
';
                        $($alert).insertBefore(that.$sortModal.find('.bars'));
                    }
                } else {
                    if ($alert.length === 1) {
                        $($alert).remove();
                    }

                    that.options.sortName = "";
                    that.onMultipleSort();
                    that.$sortModal.modal('hide');
                }
            });

            if (that.options.sortPriority === null || that.options.sortPriority.length === 0) {
                if (that.options.sortName) {
                    that.options.sortPriority = [{
                        sortName: that.options.sortName,
                        sortOrder: that.options.sortOrder
                    }];
                }
            }

            if (that.options.sortPriority !== null && that.options.sortPriority.length > 0) {
                if ($rows.length < that.options.sortPriority.length && typeof that.options.sortPriority === 'object') {
                    for (var i = 0; i < that.options.sortPriority.length; i++) {
                        that.addLevel(i, that.options.sortPriority[i]);
                    }
                }
            } else {
                that.addLevel(0);
            }

            that.setButtonStates();
        }
    };

    $.extend($.fn.bootstrapTable.defaults, {
        showMultiSort: false,
        sortPriority: null,
        onMultipleSort: function() {
            return false;
        }
    });

    $.extend($.fn.bootstrapTable.defaults.icons, {
        sort: 'glyphicon-sort',
        plus: 'glyphicon-plus',
        minus: 'glyphicon-minus'
    });

    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
        'multiple-sort.bs.table': 'onMultipleSort'
    });

    $.extend($.fn.bootstrapTable.locales, {
        formatMultipleSort: function() {
            return 'Multiple Sort';
        },
        formatAddLevel: function() {
            return "Add Level";
        },
        formatDeleteLevel: function() {
            return "Delete Level";
        },
        formatColumn: function() {
            return "Column";
        },
        formatOrder: function() {
            return "Order";
        },
        formatSortBy: function() {
            return "Sort by";
        },
        formatThenBy: function() {
            return "Then by";
        },
        formatSort: function() {
            return "Sort";
        },
        formatCancel: function() {
            return "Cancel";
        },
        formatDuplicateAlertTitle: function() {
            return "Duplicate(s) detected!";
        },
        formatDuplicateAlertDescription: function() {
            return "Please remove or change any duplicate column.";
        }
    });

    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);

    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _initToolbar = BootstrapTable.prototype.initToolbar;

    BootstrapTable.prototype.initToolbar = function() {
        this.showToolbar = true;
        var that = this,
            sortModalId = '#sortModal_' + this.$el.attr('id');
        this.$sortModal = $(sortModalId);

        _initToolbar.apply(this, Array.prototype.slice.apply(arguments));

        if (this.options.showMultiSort) {
            var $btnGroup = this.$toolbar.find('>.btn-group').first(),
                $multiSortBtn = this.$toolbar.find('div.multi-sort');

            if (!$multiSortBtn.length) {
                $multiSortBtn = '  <button class="multi-sort btn btn-default' + (this.options.iconSize === undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" data-toggle="modal" data-target="' + sortModalId + '" title="' + this.options.formatMultipleSort() + '">';
                $multiSortBtn += '     ';
                $multiSortBtn += '</button>';

                $btnGroup.append($multiSortBtn);

                showSortModal(that);
            }

            this.$el.on('sort.bs.table', function() {
                isSingleSort = true;
            });

            this.$el.on('multiple-sort.bs.table', function() {
                isSingleSort = false;
            });

            this.$el.on('load-success.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.onMultipleSort();
                }
            });

            this.$el.on('column-switch.bs.table', function(field, checked) {
                for (var i = 0; i < that.options.sortPriority.length; i++) {
                    if (that.options.sortPriority[i].sortName === checked) {
                        that.options.sortPriority.splice(i, 1);
                    }
                }

                that.assignSortableArrows();
                that.$sortModal.remove();
                showSortModal(that);
            });

            this.$el.on('reset-view.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.assignSortableArrows();
                }
            });
        }
    };

    BootstrapTable.prototype.onMultipleSort = function() {
        var that = this;

        var cmp = function(x, y) {
            return x > y ? 1 : x < y ? -1 : 0;
        };

        var arrayCmp = function(a, b) {
            var arr1 = [],
                arr2 = [];

            for (var i = 0; i < that.options.sortPriority.length; i++) {
                var order = that.options.sortPriority[i].sortOrder === 'desc' ? -1 : 1,
                    aa = a[that.options.sortPriority[i].sortName],
                    bb = b[that.options.sortPriority[i].sortName];

                if (aa === undefined || aa === null) {
                    aa = '';
                }
                if (bb === undefined || bb === null) {
                    bb = '';
                }
                if ($.isNumeric(aa) && $.isNumeric(bb)) {
                    aa = parseFloat(aa);
                    bb = parseFloat(bb);
                }
                if (typeof aa !== 'string') {
                    aa = aa.toString();
                }

                arr1.push(
                    order * cmp(aa, bb));
                arr2.push(
                    order * cmp(bb, aa));
            }

            return cmp(arr1, arr2);
        };

        this.data.sort(function(a, b) {
            return arrayCmp(a, b);
        });

        this.initBody();
        this.assignSortableArrows();
        this.trigger('multiple-sort');
    };

    BootstrapTable.prototype.addLevel = function(index, sortPriority) {
        var text = index === 0 ? this.options.formatSortBy() : this.options.formatThenBy();

        this.$sortModal.find('tbody')
            .append($('
')
                .append($('').text(text))
                .append($('').append($('<select class="form-control multi-sort-name">')))
                .append($('').append($('<select class="form-control multi-sort-order">')))
        );

        var $multiSortName = this.$sortModal.find('.multi-sort-name').last(),
            $multiSortOrder = this.$sortModal.find('.multi-sort-order').last();

        $.each(this.columns, function (i, column) {
            if (column.sortable === false || column.visible === false) {
                return true;
            }
            $multiSortName.append('<option value="' + column.field + '">' + column.title + '</option>');
        });

        $.each(sort_order, function(value, order) {
            $multiSortOrder.append('<option value="' + value + '">' + order + '</option>');
        });

        if (sortPriority !== undefined) {
            $multiSortName.find('option[value="' + sortPriority.sortName + '"]').attr("selected", true);
            $multiSortOrder.find('option[value="' + sortPriority.sortOrder + '"]').attr("selected", true);
        }
    };

    BootstrapTable.prototype.assignSortableArrows = function() {
        var that = this,
            headers = that.$header.find('th');

        for (var i = 0; i < headers.length; i++) {
            for (var c = 0; c < that.options.sortPriority.length; c++) {
                if ($(headers[i]).data('field') === that.options.sortPriority[c].sortName) {
                    $(headers[i]).find('.sortable').removeClass('desc asc').addClass(that.options.sortPriority[c].sortOrder);
                }
            }
        }
    };

    BootstrapTable.prototype.setButtonStates = function() {
        var total = this.$sortModal.find('.multi-sort-name:first option').length,
            current = this.$sortModal.find('tbody tr').length;

        if (current == total) {
            this.$sortModal.find('#add').attr('disabled', 'disabled');
        }
        if (current > 1) {
            this.$sortModal.find('#delete').removeAttr('disabled');
        }
        if (current < total) {
            this.$sortModal.find('#add').removeAttr('disabled');
        }
        if (current == 1) {
            this.$sortModal.find('#delete').attr('disabled', 'disabled');
        }
    };
})(jQuery);
<commit_msg>Upgrade to sort orders so the text can be change from locales<commit_after>/**
 * @author Nadim Basalamah <dimbslmh@gmail.com>
 * @version: v1.1.0
 * https://github.com/dimbslmh/bootstrap-table/tree/master/src/extensions/multiple-sort/bootstrap-table-multiple-sort.js
 * Modification: ErwannNevou <https://github.com/ErwannNevou>
 */

(function($) {
    'use strict';

    var isSingleSort = false;

    var showSortModal = function(that) {
        var _selector = that.$sortModal.selector,
            _id = _selector.substr(1);

        if (!$(_id).hasClass("modal")) {
            var sModal = '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
            sModal += '
' + that.options.formatMultipleSort() + '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                     <button id="add" type="button" class="btn btn-default"> ' + that.options.formatAddLevel() + '</button>';
            sModal += '                                     <button id="delete" type="button" class="btn btn-default" disabled> ' + that.options.formatDeleteLevel() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                                         	';
            sModal += '
' + that.options.formatColumn() + '
	';
            sModal += '
' + that.options.formatOrder() + '
	';
            sModal += '
';
            sModal += '
';
            sModal += '

';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '                     <button type="button" class="btn btn-default" data-dismiss="modal">' + that.options.formatCancel() + '</button>';
            sModal += '                     <button type="button" class="btn btn-primary">' + that.options.formatSort() + '</button>';
            sModal += '
';
            sModal += '
';
            sModal += '
';
            sModal += '
';

            $("body").append($(sModal));

            that.$sortModal = $(_selector);
            var $rows = that.$sortModal.find("tbody > tr");

            that.$sortModal.off('click', '#add').on('click', '#add', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current < total) {
                    current++;
                    that.addLevel();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '#delete').on('click', '#delete', function() {
                var total = that.$sortModal.find('.multi-sort-name:first option').length,
                    current = that.$sortModal.find('tbody tr').length;

                if (current > 1 && current <= total) {
                    current--;
                    that.$sortModal.find('tbody tr:last').remove();
                    that.setButtonStates();
                }
            });

            that.$sortModal.off('click', '.btn-primary').on('click', '.btn-primary', function() {
                var $rows = that.$sortModal.find("tbody > tr"),
                    $alert = that.$sortModal.find('div.alert'),
                    fields = [],
                    results = [];

                that.options.sortPriority = $.map($rows, function(row) {
                    var $row = $(row),
                        name = $row.find('.multi-sort-name').val(),
                        order = $row.find('.multi-sort-order').val();

                    fields.push(name);

                    return {
                        sortName: name,
                        sortOrder: order
                    };
                });

                var sorted_fields = fields.sort();

                for (var i = 0; i < fields.length - 1; i++) {
                    if (sorted_fields[i + 1] == sorted_fields[i]) {
                        results.push(sorted_fields[i]);
                    }
                }

                if (results.length > 0) {
                    if ($alert.length === 0) {
                        $alert = '
' + that.options.formatDuplicateAlertTitle() + ' ' + that.options.formatDuplicateAlertDescription() + '
';
                        $($alert).insertBefore(that.$sortModal.find('.bars'));
                    }
                } else {
                    if ($alert.length === 1) {
                        $($alert).remove();
                    }

                    that.options.sortName = "";
                    that.onMultipleSort();
                    that.$sortModal.modal('hide');
                }
            });

            if (that.options.sortPriority === null || that.options.sortPriority.length === 0) {
                if (that.options.sortName) {
                    that.options.sortPriority = [{
                        sortName: that.options.sortName,
                        sortOrder: that.options.sortOrder
                    }];
                }
            }

            if (that.options.sortPriority !== null && that.options.sortPriority.length > 0) {
                if ($rows.length < that.options.sortPriority.length && typeof that.options.sortPriority === 'object') {
                    for (var i = 0; i < that.options.sortPriority.length; i++) {
                        that.addLevel(i, that.options.sortPriority[i]);
                    }
                }
            } else {
                that.addLevel(0);
            }

            that.setButtonStates();
        }
    };

    $.extend($.fn.bootstrapTable.defaults, {
        showMultiSort: false,
        sortPriority: null,
        onMultipleSort: function() {
            return false;
        }
    });

    $.extend($.fn.bootstrapTable.defaults.icons, {
        sort: 'glyphicon-sort',
        plus: 'glyphicon-plus',
        minus: 'glyphicon-minus'
    });

    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
        'multiple-sort.bs.table': 'onMultipleSort'
    });

    $.extend($.fn.bootstrapTable.locales, {
        formatMultipleSort: function() {
            return 'Multiple Sort';
        },
        formatAddLevel: function() {
            return "Add Level";
        },
        formatDeleteLevel: function() {
            return "Delete Level";
        },
        formatColumn: function() {
            return "Column";
        },
        formatOrder: function() {
            return "Order";
        },
        formatSortBy: function() {
            return "Sort by";
        },
        formatThenBy: function() {
            return "Then by";
        },
        formatSort: function() {
            return "Sort";
        },
        formatCancel: function() {
            return "Cancel";
        },
        formatDuplicateAlertTitle: function() {
            return "Duplicate(s) detected!";
        },
        formatDuplicateAlertDescription: function() {
            return "Please remove or change any duplicate column.";
        },
        sortOrders : function () {
            return {
              asc: 'Ascending',
              desc: 'Descending'
            }
        }
    });

    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);

    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _initToolbar = BootstrapTable.prototype.initToolbar;

    BootstrapTable.prototype.initToolbar = function() {
        this.showToolbar = true;
        var that = this,
            sortModalId = '#sortModal_' + this.$el.attr('id');
        this.$sortModal = $(sortModalId);

        _initToolbar.apply(this, Array.prototype.slice.apply(arguments));

        if (this.options.showMultiSort) {
            var $btnGroup = this.$toolbar.find('>.btn-group').first(),
                $multiSortBtn = this.$toolbar.find('div.multi-sort');

            if (!$multiSortBtn.length) {
                $multiSortBtn = '  <button class="multi-sort btn btn-default' + (this.options.iconSize === undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" data-toggle="modal" data-target="' + sortModalId + '" title="' + this.options.formatMultipleSort() + '">';
                $multiSortBtn += '     ';
                $multiSortBtn += '</button>';

                $btnGroup.append($multiSortBtn);

                showSortModal(that);
            }

            this.$el.on('sort.bs.table', function() {
                isSingleSort = true;
            });

            this.$el.on('multiple-sort.bs.table', function() {
                isSingleSort = false;
            });

            this.$el.on('load-success.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.onMultipleSort();
                }
            });

            this.$el.on('column-switch.bs.table', function(field, checked) {
                for (var i = 0; i < that.options.sortPriority.length; i++) {
                    if (that.options.sortPriority[i].sortName === checked) {
                        that.options.sortPriority.splice(i, 1);
                    }
                }

                that.assignSortableArrows();
                that.$sortModal.remove();
                showSortModal(that);
            });

            this.$el.on('reset-view.bs.table', function() {
                if (!isSingleSort && that.options.sortPriority !== null && typeof that.options.sortPriority === 'object') {
                    that.assignSortableArrows();
                }
            });
        }
    };

    BootstrapTable.prototype.onMultipleSort = function() {
        var that = this;

        var cmp = function(x, y) {
            return x > y ? 1 : x < y ? -1 : 0;
        };

        var arrayCmp = function(a, b) {
            var arr1 = [],
                arr2 = [];

            for (var i = 0; i < that.options.sortPriority.length; i++) {
                var order = that.options.sortPriority[i].sortOrder === 'desc' ? -1 : 1,
                    aa = a[that.options.sortPriority[i].sortName],
                    bb = b[that.options.sortPriority[i].sortName];

                if (aa === undefined || aa === null) {
                    aa = '';
                }
                if (bb === undefined || bb === null) {
                    bb = '';
                }
                if ($.isNumeric(aa) && $.isNumeric(bb)) {
                    aa = parseFloat(aa);
                    bb = parseFloat(bb);
                }
                if (typeof aa !== 'string') {
                    aa = aa.toString();
                }

                arr1.push(
                    order * cmp(aa, bb));
                arr2.push(
                    order * cmp(bb, aa));
            }

            return cmp(arr1, arr2);
        };

        this.data.sort(function(a, b) {
            return arrayCmp(a, b);
        });

        this.initBody();
        this.assignSortableArrows();
        this.trigger('multiple-sort');
    };

    BootstrapTable.prototype.addLevel = function(index, sortPriority) {
        var text = index === 0 ? this.options.formatSortBy() : this.options.formatThenBy();

        this.$sortModal.find('tbody')
            .append($('
')
                .append($('').text(text))
                .append($('').append($('<select class="form-control multi-sort-name">')))
                .append($('').append($('<select class="form-control multi-sort-order">')))
        );

        var $multiSortName = this.$sortModal.find('.multi-sort-name').last(),
            $multiSortOrder = this.$sortModal.find('.multi-sort-order').last();

        $.each(this.columns, function (i, column) {
            if (column.sortable === false || column.visible === false) {
                return true;
            }
            $multiSortName.append('<option value="' + column.field + '">' + column.title + '</option>');
        });

        $.each(this.options.sortOrders(), function(value, order) {
            $multiSortOrder.append('<option value="' + value + '">' + order + '</option>');
        });

        if (sortPriority !== undefined) {
            $multiSortName.find('option[value="' + sortPriority.sortName + '"]').attr("selected", true);
            $multiSortOrder.find('option[value="' + sortPriority.sortOrder + '"]').attr("selected", true);
        }
    };

    BootstrapTable.prototype.assignSortableArrows = function() {
        var that = this,
            headers = that.$header.find('th');

        for (var i = 0; i < headers.length; i++) {
            for (var c = 0; c < that.options.sortPriority.length; c++) {
                if ($(headers[i]).data('field') === that.options.sortPriority[c].sortName) {
                    $(headers[i]).find('.sortable').removeClass('desc asc').addClass(that.options.sortPriority[c].sortOrder);
                }
            }
        }
    };

    BootstrapTable.prototype.setButtonStates = function() {
        var total = this.$sortModal.find('.multi-sort-name:first option').length,
            current = this.$sortModal.find('tbody tr').length;

        if (current == total) {
            this.$sortModal.find('#add').attr('disabled', 'disabled');
        }
        if (current > 1) {
            this.$sortModal.find('#delete').removeAttr('disabled');
        }
        if (current < total) {
            this.$sortModal.find('#add').removeAttr('disabled');
        }
        if (current == 1) {
            this.$sortModal.find('#delete').attr('disabled', 'disabled');
        }
    };
})(jQuery);
<|endoftext|>


<commit_before>import React, {Component} from 'react';

import Table from 'src/Table';
import Switcher from 'src/Switcher';
import IconButton from 'src/IconButton';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Table.json';

import 'sass/containers/app/modules/layout/TableExamples.scss';

export default class TableExamples extends Component {

    constructor(props) {

        super(props);

        this.columns = [{
            header: 'ID',
            sortable: true,
            sortProp: 'id',
            renderer: 'id',
            headerClassName: 'test-header',
            cellClassName: 'test-cell'
        }, {
            header: 'Name',
            sortable: true,
            sortProp: 'firstName',
            renderer: '${firstName} - ${lastName}'
        }, {
            header: 'Status',
            renderer(rowData) {
                return <Switcher value={!rowData.disabled}
                                 size="small"
                                 onClick={(e) => {
                                     e.stopPropagation();
                                 }}/>;
            }
        }];

        this.pageSizes = [{
            value: 10,
            text: '10 / page'
        }, {
            value: 20,
            text: '20 / page'
        }, {
            value: 30,
            text: '30 / page'
        }, {
            value: 40,
            text: '40 / page'
        }, {
            value: 50,
            text: '50 / page'
        }];

        this.state = {
            data: this.generateData()
        };

        this.deleteRow = ::this.deleteRow;

    }

    generateData(size = 100) {

        let data = [];
        for (let i = 0; i < size; i++) {
            data.push({
                id: i,
                firstName: `firstNameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa${i}`,
                lastName: `lastName${i}`
            });
        }

        return data;

    }

    deleteRow(id) {

        const {data} = this.state,
            newData = data.filter(item => item.id !== id);

        this.setState({
            data: newData
        });

    }

    render() {

        const {data} = this.state,
            {deleteRow} = this;

        return (

Table

                    Tables are used to display data and to organize it.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="With isPagging"/>

A simple Table example.

                            <Table data={data}
                                   columns={[...this.columns, {
                                       header: 'action',
                                       renderer(rowData) {
                                           return (
                                               <IconButton iconCls="fas fa-trash-alt"
                                                           onClick={() => {
                                                               deleteRow(rowData.id);
                                                           }}/>
                                           );
                                       }
                                   }]}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With hasLineNumber and isMultiSelect"/>

A more complex example.Set the hasLineNumber and isMultiSelect
                                to true for showLineNumber and checkbox.

                            <Table columns={this.columns}
                                   selectMode={Table.SelectMode.MULTI_SELECT}
                                   data={data}
                                   paggingSelectedCountVisible={true}
                                   defaultPageSize={20}
                                   pageSizes={this.pageSizes}
                                   useFullPagging={true}
                                   sortAscIconCls="fas fa-caret-up"
                                   sortDescIconCls="fas fa-caret-down"
                                   onPageChange={(page, pageSize) => {
                                       console.log(`page: ${page}, pageSize: ${pageSize}`);
                                   }}
                                   onChange={value => {
                                       console.log(value);
                                   }}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="Empty"/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};<commit_msg>update TableExamples<commit_after>import React, {Component} from 'react';

import Table from 'src/Table';
import Switcher from 'src/Switcher';
import IconButton from 'src/IconButton';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Table.json';

import 'sass/containers/app/modules/layout/TableExamples.scss';

class TableExamples extends Component {

    constructor(props) {

        super(props);

        this.columns = [{
            header: 'ID',
            sortable: true,
            sortProp: 'id',
            renderer: 'id',
            headerClassName: 'test-header',
            cellClassName: 'test-cell'
        }, {
            header: 'Name',
            sortable: true,
            sortProp: 'firstName',
            renderer: '${firstName} - ${lastName}'
        }, {
            header: 'Status',
            renderer(rowData) {
                return <Switcher value={!rowData.disabled}
                                 size="small"
                                 onClick={(e) => {
                                     e.stopPropagation();
                                 }}/>;
            }
        }];

        this.pageSizes = [{
            value: 10,
            text: '10 / page'
        }, {
            value: 20,
            text: '20 / page'
        }, {
            value: 30,
            text: '30 / page'
        }, {
            value: 40,
            text: '40 / page'
        }, {
            value: 50,
            text: '50 / page'
        }];

        this.state = {
            data: this.generateData()
        };

    }

    generateData = (size = 100) => {

        let data = [];
        for (let i = 0; i < size; i++) {
            data.push({
                id: i,
                firstName: `firstNameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa${i}`,
                lastName: `lastName${i}`
            });
        }

        return data;

    };

    deleteRow = id => {

        const {data} = this.state,
            newData = data.filter(item => item.id !== id);

        this.setState({
            data: newData
        });

    };

    render() {

        const {data} = this.state;

        return (

Table

                    Tables are used to display data and to organize it.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="With isPagging"/>

A simple Table example.

                                           <IconButton iconCls="fas fa-trash-alt"
                                                       onClick={() => this.deleteRow(rowData.id)}/>
                                   }]}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With hasLineNumber and isMultiSelect"/>

A more complex example.Set the hasLineNumber and isMultiSelect
                                to true for showLineNumber and checkbox.

                            <Table columns={this.columns}
                                   selectMode={Table.SelectMode.MULTI_SELECT}
                                   data={data}
                                   paggingSelectedCountVisible={true}
                                   defaultPageSize={20}
                                   pageSizes={this.pageSizes}
                                   useFullPagging={true}
                                   sortAscIconCls="fas fa-caret-up"
                                   sortDescIconCls="fas fa-caret-down"
                                   onPageChange={(page, pageSize) => {
                                       console.log(`page: ${page}, pageSize: ${pageSize}`);
                                   }}
                                   onChange={value => {
                                       console.log(value);
                                   }}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="Empty"/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};

export default TableExamples;<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");

module.exports = function testDir(dir) {
    fs.readdir(dir, function (err, files) {
        if (!files) {
            return;
        }

        files.forEach(function (file) {
            var fullPath = path.join(dir, file);

            fs.stat(fullPath, function (err, stat) {
                if (!stat) {
                    return;
                }

                if (stat.isDirectory()) {
                    testDir(fullPath);
                } else {
                    if (/\.js$/.test(file) && !/browser/.test(fullPath) &&
                        (!filter || filter.test(fullPath))) {
                        require("./" + fullPath.replace(/\.js$/, ""));
                    }
                }
            });
        });
    });
};
<commit_msg>Allow runner to accept a filter<commit_after>var fs = require("fs");
var path = require("path");

module.exports = function testDir(dir, filter) {
    fs.readdir(dir, function (err, files) {
        if (!files) {
            return;
        }

        files.forEach(function (file) {
            var fullPath = path.join(dir, file);

            fs.stat(fullPath, function (err, stat) {
                if (!stat) {
                    return;
                }

                if (stat.isDirectory()) {
                    testDir(fullPath);
                } else {
                    if (/\.js$/.test(file) && !/browser/.test(fullPath) &&
                        (!filter || filter.test(fullPath))) {
                        require("./" + fullPath.replace(/\.js$/, ""));
                    }
                }
            });
        });
    });
};
<|endoftext|>